Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/dm/models/ve.dm.MWImageModel.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel MWImageModel class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * MediaWiki image model.
10 *
11 * @class
12 * @mixes OO.EventEmitter
13 *
14 * @constructor
15 * @param {ve.dm.Document} parentDoc Document that contains or will contain the image
16 * @param {Object} [config] Configuration options
17 * @param {string} [config.resourceName] The resource name of the given media file
18 * @param {Object} [config.currentDimensions={}] Current dimensions, width & height
19 * @param {Object} [config.minDimensions={}] Minimum dimensions, width & height
20 * @param {boolean} [config.isDefaultSize=false] Object is using its default size dimensions
21 */
22 ve.dm.MWImageModel = function VeDmMWImageModel( parentDoc, config ) {
23 config = config || {};
24
25 // Mixin constructors
26 OO.EventEmitter.call( this );
27
28 // Properties
29 this.attributesCache = {};
30
31 // Image properties
32 this.parentDoc = parentDoc;
33 this.captionDoc = null;
34 this.caption = null;
35 this.mediaType = null;
36 this.altText = '';
37 this.type = null;
38 this.alignment = null;
39 this.scalable = null;
40 this.sizeType = null;
41 this.border = false;
42 this.borderable = false;
43 this.defaultDimensions = null;
44 this.changedImageSource = false;
45
46 this.imageSrc = '';
47 this.imageResourceName = '';
48 this.imageHref = '';
49 this.imageClassAttr = null;
50
51 // FIXME: This is blindly being preserved but may not apply if, say,
52 // a link is no longer pointing to a file description page. When support
53 // for editing the |link= media option is added, take it into account.
54 this.imgWrapperClassAttr = null;
55
56 this.boundingBox = null;
57 this.initialHash = {};
58
59 // Get wiki default thumbnail size
60 this.defaultThumbSize = mw.config.get( 'wgVisualEditorConfig' )
61 .thumbLimits[ mw.user.options.get( 'thumbsize' ) ];
62
63 if ( config.resourceName ) {
64 this.setImageResourceName( config.resourceName );
65 }
66
67 // Create scalable
68 const currentDimensions = config.currentDimensions || {};
69 const minDimensions = config.minDimensions || {};
70
71 const scalable = new ve.dm.Scalable( {
72 currentDimensions: {
73 width: currentDimensions.width,
74 height: currentDimensions.height
75 },
76 minDimensions: {
77 width: minDimensions.width || 1,
78 height: minDimensions.height || 1
79 },
80 defaultSize: !!config.isDefaultSize
81 } );
82 // Set the initial scalable, connect it to events
83 // and request an update from the API
84 this.attachScalable( scalable );
85 };
86
87 /* Inheritance */
88
89 OO.mixinClass( ve.dm.MWImageModel, OO.EventEmitter );
90
91 /* Events */
92
93 /**
94 * Change of image alignment or of having alignment at all
95 *
96 * @event ve.dm.MWImageModel#alignmentChange
97 * @param {string} Alignment 'left', 'right', 'center' or 'none'
98 */
99
100 /**
101 * Change in size type between default and custom
102 *
103 * @event ve.dm.MWImageModel#sizeDefaultChange
104 * @param {boolean} Image is default size
105 */
106
107 /**
108 * Change in the image type
109 *
110 * @event ve.dm.MWImageModel#typeChange
111 * @param {string} Image type 'thumb', 'frame', 'frameless' or 'none'
112 */
113
114 /* Static Properties */
115
116 ve.dm.MWImageModel.static.infoCache = {};
117
118 /* Static Methods */
119
120 /**
121 * Create a new image node based on given parameters.
122 *
123 * @param {Object} attributes Image attributes
124 * @param {string} [imageType] Image node type 'mwInlineImage' or 'mwBlockImage'.
125 * Defaults to 'mwBlockImage'
126 * @return {ve.dm.MWImageNode} An image node
127 */
128 ve.dm.MWImageModel.static.createImageNode = function ( attributes, imageType ) {
129 const defaultThumbSize = mw.config.get( 'wgVisualEditorConfig' )
130 .thumbLimits[ mw.user.options.get( 'thumbsize' ) ];
131
132 const attrs = ve.extendObject( {
133 mediaClass: 'File',
134 mediaTag: 'img',
135 type: 'thumb',
136 align: 'default',
137 width: defaultThumbSize,
138 mediaType: 'BITMAP',
139 defaultSize: true,
140 imageClassAttr: 'mw-file-element'
141 }, attributes );
142
143 if ( attrs.defaultSize ) {
144 const newDimensions = ve.dm.MWImageNode.static.scaleToThumbnailSize( attrs, attrs.mediaType );
145 if ( newDimensions ) {
146 attrs.width = newDimensions.width;
147 attrs.height = newDimensions.height;
148 }
149 }
150
151 imageType = imageType || 'mwBlockImage';
152
153 const newNode = ve.dm.nodeFactory.createFromElement( {
154 type: imageType,
155 attributes: attrs
156 } );
157
158 ve.dm.MWImageNode.static.syncScalableToType( attrs.type, attrs.mediaType, newNode.getScalable() );
159
160 return newNode;
161 };
162
163 /**
164 * Load from image data with scalable information.
165 *
166 * @param {Object} attrs Image node attributes
167 * @param {ve.dm.Document} parentDoc Document that contains or will contain the image
168 * @return {ve.dm.MWImageModel} Image model
169 */
170 ve.dm.MWImageModel.static.newFromImageAttributes = function ( attrs, parentDoc ) {
171 const imgModel = new ve.dm.MWImageModel(
172 parentDoc,
173 {
174 resourceName: attrs.resource,
175 currentDimensions: {
176 width: attrs.width,
177 height: attrs.height
178 },
179 defaultSize: !!attrs.defaultSize
180 }
181 );
182
183 // Cache the attributes so we can create a new image without
184 // losing any existing information
185 imgModel.cacheOriginalImageAttributes( attrs );
186
187 imgModel.setImageSource( attrs.src );
188 imgModel.setFilename( new mw.Title( mw.libs.ve.normalizeParsoidResourceName( attrs.resource ) ).getMainText() );
189 imgModel.setImageHref( attrs.href );
190 imgModel.setImageClassAttr( attrs.imageClassAttr );
191 imgModel.setImgWrapperClassAttr( attrs.imgWrapperClassAttr );
192
193 // Set bounding box
194 imgModel.setBoundingBox( {
195 width: attrs.width,
196 height: attrs.height
197 } );
198
199 // Collect all the information
200 imgModel.toggleBorder( !!attrs.borderImage );
201 imgModel.setAltText( attrs.alt || '' );
202
203 imgModel.setType( attrs.type );
204
205 // Fix cases where alignment is undefined
206 // Inline images have no 'align' (they have 'valign' instead)
207 // But we do want an alignment case for these in case they
208 // are transformed to block images
209 imgModel.setAlignment( attrs.align || 'default' );
210
211 // Default size
212 imgModel.toggleDefaultSize( !!attrs.defaultSize );
213
214 // TODO: When scale/upright is available, set the size
215 // type accordingly
216 imgModel.setSizeType( imgModel.isDefaultSize() ? 'default' : 'custom' );
217
218 return imgModel;
219 };
220
221 /**
222 * Load from existing image node.
223 *
224 * @param {ve.dm.MWImageNode} node Image node
225 * @return {ve.dm.MWImageModel} Image model
226 */
227 ve.dm.MWImageModel.static.newFromImageNode = function ( node ) {
228 return ve.dm.MWImageModel.static.newFromImageAttributes( node.getAttributes(), node.getDocument() );
229 };
230
231 /* Methods */
232
233 /**
234 * Get the hash object of the current image model state.
235 *
236 * @return {Object}
237 */
238 ve.dm.MWImageModel.prototype.getHashObject = function () {
239 const hash = {
240 filename: this.getFilename(),
241 altText: this.getAltText(),
242 type: this.getType(),
243 alignment: this.getAlignment(),
244 sizeType: this.getSizeType(),
245 border: this.hasBorder(),
246 borderable: this.isBorderable()
247 };
248
249 if ( this.getScalable() ) {
250 hash.scalable = {
251 currentDimensions: ve.copy( this.getScalable().getCurrentDimensions() ),
252 isDefault: this.getScalable().isDefault()
253 };
254 }
255 return hash;
256 };
257
258 /**
259 * Normalize the source url by stripping the protocol off.
260 * This is done so when an image is replaced with the same image,
261 * the imageModel can recognize that nothing has actually changed.
262 *
263 * Example:
264 * 'http://upload.wikimedia.org/wikipedia/commons/0/Foo.png'
265 * to '//upload.wikimedia.org/wikipedia/commons/0/Foo.png'
266 *
267 * @return {string} Normalized image source
268 */
269 ve.dm.MWImageModel.prototype.getNormalizedImageSource = function () {
270 // Strip the url prefix 'http' / 'https' etc
271 return this.getImageSource().replace( /^https?:\/\//, '//' );
272 };
273
274 /**
275 * Adjust the model parameters based on a new image
276 *
277 * @param {Object} attrs New image source attributes
278 * @param {Object} [APIinfo] The image's API info
279 * @throws {Error} Image has insufficient details to compute the imageModel details.
280 */
281 ve.dm.MWImageModel.prototype.changeImageSource = function ( attrs, APIinfo ) {
282 this.changedImageSource = true;
283
284 if ( attrs.mediaType ) {
285 this.setMediaType( attrs.mediaType );
286 }
287 if ( attrs.href ) {
288 this.setImageHref( attrs.href );
289 }
290
291 // FIXME: Account for falsey but present values
292 if ( attrs.imageClassAttr ) {
293 this.setImageClassAttr( attrs.imageClassAttr );
294 }
295
296 // FIXME: Account for falsey but present values
297 if ( attrs.imgWrapperClassAttr ) {
298 this.setImgWrapperClassAttr( attrs.imgWrapperClassAttr );
299 }
300
301 if ( attrs.resource ) {
302 this.setImageResourceName( attrs.resource );
303 this.setFilename( new mw.Title( mw.libs.ve.normalizeParsoidResourceName( attrs.resource ) ).getMainText() );
304 }
305
306 if ( attrs.src ) {
307 this.setImageSource( attrs.src );
308 }
309
310 // Remove the scalable default and original dimensions
311 this.scalable.clearOriginalDimensions();
312 this.scalable.clearDefaultDimensions();
313 this.scalable.clearMaxDimensions();
314 this.scalable.clearMinDimensions();
315 // This is a different image so clear the attributes cache
316 delete this.attributesCache.originalWidth;
317 delete this.attributesCache.originalHeight;
318
319 // If we already have dimensions from the API, use them
320 if ( APIinfo ) {
321 this.scalable.setOriginalDimensions( {
322 width: APIinfo.width,
323 height: APIinfo.height
324 } );
325 // Update media type
326 this.setMediaType( APIinfo.mediatype );
327 // Update defaults
328 ve.dm.MWImageNode.static.syncScalableToType(
329 this.getType(),
330 APIinfo.mediatype,
331 this.scalable
332 );
333 this.updateScalableDetails( {
334 width: APIinfo.width,
335 height: APIinfo.height
336 } );
337 } else {
338 // Call for updated scalable if we don't have dimensions from the API info
339 if ( this.getFilename() ) {
340 // Update anyway
341 ve.dm.MWImageNode.static.getScalablePromise( this.getFilename() ).done( ( info ) => {
342 this.scalable.setOriginalDimensions( {
343 width: info.width,
344 height: info.height
345 } );
346 // Update media type
347 this.setMediaType( info.mediatype );
348 // Update defaults
349 ve.dm.MWImageNode.static.syncScalableToType(
350 this.getType(),
351 info.mediatype,
352 this.scalable
353 );
354 this.updateScalableDetails( {
355 width: info.width,
356 height: info.height
357 } );
358 } );
359 } else {
360 throw new Error( 'Cannot compute details for an image without remote filename and without sizing info.' );
361 }
362 }
363 };
364
365 /**
366 * Get the current image node type according to the attributes.
367 * If either of the parameters are given, the node type is tested
368 * against them, otherwise, it is tested against the current image
369 * parameters.
370 *
371 * @param {string} [imageType] Optional. Image type.
372 * @param {string} [align] Optional. Image alignment.
373 * @return {string} Node type 'mwInlineImage' or 'mwBlockImage'
374 */
375 ve.dm.MWImageModel.prototype.getImageNodeType = function ( imageType, align ) {
376 imageType = imageType || this.getType();
377
378 if (
379 ( this.getType() === 'frameless' || this.getType() === 'none' ) &&
380 ( !this.isAligned( align ) || this.isDefaultAligned( imageType, align ) )
381 ) {
382 return 'mwInlineImage';
383 } else {
384 return 'mwBlockImage';
385 }
386 };
387
388 /**
389 * Get the original bounding box
390 *
391 * @return {Object} Bounding box with width and height
392 */
393 ve.dm.MWImageModel.prototype.getBoundingBox = function () {
394 return this.boundingBox;
395 };
396
397 /**
398 * Update an existing image node by changing its attributes
399 *
400 * @param {ve.dm.MWImageNode} node Image node to update
401 * @param {ve.dm.Surface} surfaceModel Surface model of main document
402 */
403 ve.dm.MWImageModel.prototype.updateImageNode = function ( node, surfaceModel ) {
404 const doc = surfaceModel.getDocument();
405
406 // Update the caption
407 if ( node.getType() === 'mwBlockImage' ) {
408 let captionNode = node.getCaptionNode();
409 if ( !captionNode ) {
410 // There was no caption before, so insert one now
411 surfaceModel.getFragment()
412 .adjustLinearSelection( 1 )
413 .collapseToStart()
414 .insertContent( [ { type: 'mwImageCaption' }, { type: '/mwImageCaption' } ] );
415 // Update the caption node
416 captionNode = node.getCaptionNode();
417 }
418
419 const captionRange = captionNode.getRange();
420
421 // Remove contents of old caption
422 surfaceModel.change(
423 ve.dm.TransactionBuilder.static.newFromRemoval(
424 doc,
425 captionRange,
426 true
427 )
428 );
429
430 // Add contents of new caption
431 surfaceModel.change(
432 ve.dm.TransactionBuilder.static.newFromDocumentInsertion(
433 doc,
434 captionRange.start,
435 this.getCaptionDocument()
436 )
437 );
438 }
439
440 // Update attributes
441 surfaceModel.change(
442 ve.dm.TransactionBuilder.static.newFromAttributeChanges(
443 doc,
444 node.getOffset(),
445 this.getUpdatedAttributes()
446 )
447 );
448 };
449
450 /**
451 * Insert image into a surface.
452 *
453 * Image is inserted at the current fragment position.
454 *
455 * @param {ve.dm.SurfaceFragment} fragment Fragment covering range to insert at
456 * @return {ve.dm.SurfaceFragment} Fragment covering inserted image
457 * @throws {Error} Unknown image node type
458 */
459 ve.dm.MWImageModel.prototype.insertImageNode = function ( fragment ) {
460 const nodeType = this.getImageNodeType(),
461 surfaceModel = fragment.getSurface();
462
463 if ( !( fragment.getSelection() instanceof ve.dm.LinearSelection ) ) {
464 return fragment;
465 }
466
467 const selectedNode = fragment.getSelectedNode();
468
469 // If there was a previous node, remove it first
470 if ( selectedNode ) {
471 // Remove the old image
472 fragment.removeContent();
473 }
474
475 const contentToInsert = this.getData();
476
477 let offset;
478 switch ( nodeType ) {
479 case 'mwInlineImage':
480 if ( selectedNode && selectedNode.type === 'mwBlockImage' ) {
481 // If converting from a block image, create a wrapper paragraph for the inline image to go in.
482 fragment.insertContent( [ { type: 'paragraph', internal: { generated: 'wrapper' } }, { type: '/paragraph' } ] );
483 offset = fragment.getSelection().getRange().start + 1;
484 } else {
485 // Try to put the image inside the nearest content node
486 offset = fragment.getDocument().data.getNearestContentOffset( fragment.getSelection().getRange().start );
487 }
488 if ( offset > -1 ) {
489 fragment = fragment.clone( new ve.dm.LinearSelection( new ve.Range( offset ) ) );
490 }
491 fragment.insertContent( contentToInsert );
492 return fragment;
493
494 case 'mwBlockImage':
495 // Try to put the image in front of the structural node
496 offset = fragment.getDocument().data.getNearestStructuralOffset( fragment.getSelection().getRange().start, -1 );
497 if ( offset > -1 ) {
498 fragment = fragment.clone( new ve.dm.LinearSelection( new ve.Range( offset ) ) );
499 }
500 fragment.insertContent( contentToInsert );
501 // Add contents of new caption
502 surfaceModel.change(
503 ve.dm.TransactionBuilder.static.newFromDocumentInsertion(
504 surfaceModel.getDocument(),
505 fragment.getSelection().getRange().start + 2,
506 this.getCaptionDocument()
507 )
508 );
509 return fragment;
510
511 default:
512 throw new Error( 'Unknown image node type ' + nodeType );
513 }
514 };
515
516 /**
517 * Get linear data representation of the image
518 *
519 * @return {Array} Linear data
520 */
521 ve.dm.MWImageModel.prototype.getData = function () {
522 const originalAttrs = ve.copy( this.getOriginalImageAttributes() ),
523 editAttributes = ve.extendObject( originalAttrs, this.getUpdatedAttributes() ),
524 nodeType = this.getImageNodeType();
525
526 // Remove old classes
527 delete editAttributes.originalClasses;
528 delete editAttributes.unrecognizedClasses;
529 // Newly created images must have valid URLs, so remove the error attribute
530 if ( this.isChangedImageSource() ) {
531 delete editAttributes.isError;
532 }
533
534 const data = [
535 {
536 type: nodeType,
537 attributes: editAttributes
538 },
539 { type: '/' + nodeType }
540 ];
541
542 if ( nodeType === 'mwBlockImage' ) {
543 data.splice( 1, 0, { type: 'mwImageCaption' }, { type: '/mwImageCaption' } );
544 }
545 return data;
546 };
547
548 /**
549 * Return all updated attributes that belong to the node.
550 *
551 * @return {Object} Updated attributes
552 */
553 ve.dm.MWImageModel.prototype.getUpdatedAttributes = function () {
554 const origAttrs = this.getOriginalImageAttributes();
555
556 let currentDimensions;
557 // Adjust default dimensions if size is set to default
558 if ( this.scalable.isDefault() && this.scalable.getDefaultDimensions() ) {
559 currentDimensions = this.scalable.getDefaultDimensions();
560 } else {
561 currentDimensions = this.getCurrentDimensions();
562 }
563
564 const attrs = {
565 mediaClass: 'File',
566 mediaTag: this.getMediaTag(),
567 type: this.getType(),
568 width: currentDimensions.width,
569 height: currentDimensions.height,
570 defaultSize: this.isDefaultSize(),
571 borderImage: this.hasBorder()
572 };
573
574 if ( this.getAltText() || typeof origAttrs.alt === 'string' ) {
575 attrs.alt = this.getAltText();
576 }
577
578 if ( this.isDefaultAligned() ) {
579 attrs.align = 'default';
580 } else if ( !this.isAligned() ) {
581 attrs.align = 'none';
582 } else {
583 attrs.align = this.getAlignment();
584 }
585
586 attrs.src = this.getImageSource();
587 attrs.href = this.getImageHref();
588 attrs.imageClassAttr = this.getImageClassAttr();
589 attrs.imgWrapperClassAttr = this.getImgWrapperClassAttr();
590 attrs.resource = this.getImageResourceName();
591
592 return attrs;
593 };
594
595 /**
596 * Deal with default change on the scalable object
597 *
598 * @param {boolean} isDefault
599 */
600 ve.dm.MWImageModel.prototype.onScalableDefaultSizeChange = function ( isDefault ) {
601 this.toggleDefaultSize( isDefault );
602 };
603
604 /**
605 * Set the image file source
606 *
607 * @param {string} src The source of the given media file
608 */
609 ve.dm.MWImageModel.prototype.setImageSource = function ( src ) {
610 this.imageSrc = src;
611 };
612
613 /**
614 * Set the image file resource name
615 *
616 * @param {string} resourceName The resource name of the given image file
617 */
618 ve.dm.MWImageModel.prototype.setImageResourceName = function ( resourceName ) {
619 this.imageResourceName = resourceName;
620 };
621
622 /**
623 * Set the image href value
624 *
625 * @param {string} href The destination href of the given media file
626 */
627 ve.dm.MWImageModel.prototype.setImageHref = function ( href ) {
628 this.imageHref = href;
629 };
630
631 /**
632 * Set the original bounding box
633 *
634 * @param {Object} box Bounding box with width and height
635 */
636 ve.dm.MWImageModel.prototype.setBoundingBox = function ( box ) {
637 this.boundingBox = box;
638 };
639
640 /**
641 * Set the initial hash object of the image to be compared to when
642 * checking if the model is modified.
643 *
644 * @param {Object} hash The initial hash object
645 */
646 ve.dm.MWImageModel.prototype.storeInitialHash = function ( hash ) {
647 this.initialHash = hash;
648 };
649
650 /**
651 * Set symbolic name of media type.
652 *
653 * Example values: "BITMAP" for JPEG or PNG images; "DRAWING" for SVG graphics
654 *
655 * @param {string|undefined} type Symbolic media type name, or undefined if empty
656 */
657 ve.dm.MWImageModel.prototype.setMediaType = function ( type ) {
658 this.mediaType = type;
659 };
660
661 /**
662 * Check whether the image is set to default size
663 *
664 * @return {boolean} Default size flag on or off
665 */
666 ve.dm.MWImageModel.prototype.isDefaultSize = function () {
667 // An image with 'frame' always ignores the size specification
668 return this.scalable.isDefault() || this.getType() === 'frame';
669 };
670
671 /**
672 * Check whether the image has the border flag set
673 *
674 * @return {boolean} Border flag on or off
675 */
676 ve.dm.MWImageModel.prototype.hasBorder = function () {
677 return this.border;
678 };
679
680 /**
681 * Check whether the image source is changed
682 *
683 * @return {boolean} changedImageSource flag on or off
684 */
685 ve.dm.MWImageModel.prototype.isChangedImageSource = function () {
686 return this.changedImageSource;
687 };
688
689 /**
690 * Check whether the image has floating alignment set
691 *
692 * @param {string} [align] Optional. Alignment value to test against.
693 * @return {boolean} hasAlignment flag on or off
694 */
695 ve.dm.MWImageModel.prototype.isAligned = function ( align ) {
696 align = align || this.alignment;
697 // The image is aligned if it has alignment (not undefined and not null)
698 // and if its alignment is not 'none'.
699 // Inline images initially have null alignment value (and are not aligned)
700 return align && align !== 'none';
701 };
702
703 /**
704 * Check whether the image is set to default alignment
705 * We explicitly repeat tests so to avoid recursively calling
706 * the other methods.
707 *
708 * @param {string} [imageType] Type of the image.
709 * @param {string} [align] Optional alignment value to test against.
710 * Supplying this parameter would test whether this align parameter
711 * would mean the image is aligned to its default position.
712 * @return {boolean} defaultAlignment flag on or off
713 */
714 ve.dm.MWImageModel.prototype.isDefaultAligned = function ( imageType, align ) {
715 const alignment = align || this.getAlignment(),
716 defaultAlignment = ( this.parentDoc.getDir() === 'rtl' ) ? 'left' : 'right';
717
718 imageType = imageType || this.getType();
719 // No alignment specified means default alignment always
720 // Inline images have no align attribute; during the initialization
721 // stage of the model we have to account for that option. Later the
722 // model creates a faux alignment for inline images ('none' for default)
723 // but if initially the alignment is null or undefined, it means the image
724 // is inline without explicit alignment (which makes it default aligned)
725 if ( !alignment ) {
726 return true;
727 }
728
729 if (
730 (
731 ( imageType === 'frameless' || imageType === 'none' ) &&
732 alignment === 'none'
733 ) ||
734 (
735 ( imageType === 'thumb' || imageType === 'frame' ) &&
736 alignment === defaultAlignment
737 )
738 ) {
739 return true;
740 }
741
742 return false;
743 };
744
745 /**
746 * Check whether the image can have a border set on it
747 *
748 * @return {boolean} Border possible or not
749 */
750 ve.dm.MWImageModel.prototype.isBorderable = function () {
751 return this.borderable;
752 };
753
754 /**
755 * Get the image file resource name
756 *
757 * @return {string} resourceName The resource name of the given media file
758 */
759 ve.dm.MWImageModel.prototype.getResourceName = function () {
760 return this.imageResourceName;
761 };
762
763 /**
764 * Get the image alternate text
765 *
766 * @return {string} Alternate text
767 */
768 ve.dm.MWImageModel.prototype.getAltText = function () {
769 return this.altText || '';
770 };
771
772 /**
773 * Get image wikitext type; 'thumb', 'frame', 'frameless' or 'none/inline'
774 *
775 * @return {string} Image type
776 */
777 ve.dm.MWImageModel.prototype.getType = function () {
778 return this.type;
779 };
780
781 /**
782 * Get the image size type of the image
783 *
784 * @return {string} Size type
785 */
786 ve.dm.MWImageModel.prototype.getSizeType = function () {
787 return this.sizeType;
788 };
789
790 /**
791 * Get symbolic name of media type.
792 *
793 * Example values: "BITMAP" for JPEG or PNG images; "DRAWING" for SVG graphics
794 *
795 * @return {string|undefined} Symbolic media type name, or undefined if empty
796 */
797 ve.dm.MWImageModel.prototype.getMediaType = function () {
798 return this.mediaType;
799 };
800
801 /**
802 * Get media tag: img, video or audio
803 *
804 * @return {string} Tag name
805 */
806 ve.dm.MWImageModel.prototype.getMediaTag = function () {
807 const mediaType = this.getMediaType();
808
809 if ( mediaType === 'VIDEO' ) {
810 return 'video';
811 }
812 if ( mediaType === 'AUDIO' ) {
813 return 'audio';
814 }
815 return 'img';
816 };
817
818 /**
819 * Get image alignment 'left', 'right', 'center', 'none' or 'default'
820 *
821 * @return {string|null} Image alignment. Inline images have initial alignment
822 * value of null.
823 */
824 ve.dm.MWImageModel.prototype.getAlignment = function () {
825 return this.alignment;
826 };
827
828 /**
829 * Get image vertical alignment
830 * 'middle', 'baseline', 'sub', 'super', 'top', 'text-top', 'bottom', 'text-bottom' or 'default'
831 *
832 * @return {string} Image alignment
833 */
834 ve.dm.MWImageModel.prototype.getVerticalAlignment = function () {
835 return this.verticalAlignment;
836 };
837
838 /**
839 * Get the scalable object responsible for size manipulations
840 * for the given image
841 *
842 * @return {ve.dm.Scalable}
843 */
844 ve.dm.MWImageModel.prototype.getScalable = function () {
845 return this.scalable;
846 };
847
848 /**
849 * @typedef {Object} Dimensions
850 * @memberof ve.ui.DimensionsWidget
851 * @property {number} width The value of the width input
852 * @property {number} height The value of the height input
853 */
854
855 /**
856 * Get the image current dimensions
857 *
858 * @return {ve.ui.DimensionsWidget.Dimensions} Current dimensions width/height
859 */
860 ve.dm.MWImageModel.prototype.getCurrentDimensions = function () {
861 return this.scalable.getCurrentDimensions();
862 };
863
864 /**
865 * Get image caption document.
866 *
867 * Auto-generates a blank document if no document exists.
868 *
869 * @return {ve.dm.Document} Caption document
870 */
871 ve.dm.MWImageModel.prototype.getCaptionDocument = function () {
872 if ( !this.captionDoc ) {
873 this.captionDoc = this.parentDoc.cloneWithData( [
874 { type: 'paragraph', internal: { generated: 'wrapper' } },
875 { type: '/paragraph' },
876 { type: 'internalList' },
877 { type: '/internalList' }
878 ] );
879 }
880 return this.captionDoc;
881 };
882
883 /**
884 * Toggle the option of whether this image can or cannot have
885 * a border set on it.
886 *
887 * @param {boolean} [borderable] Set or unset borderable. If not
888 * specified, the current state is toggled.
889 */
890 ve.dm.MWImageModel.prototype.toggleBorderable = function ( borderable ) {
891 borderable = borderable !== undefined ? !!borderable : !this.isBorderable();
892
893 this.borderable = borderable;
894 };
895
896 /**
897 * Toggle the border flag of the image
898 *
899 * @param {boolean} [hasBorder] Border flag. Omit to toggle current value.
900 */
901 ve.dm.MWImageModel.prototype.toggleBorder = function ( hasBorder ) {
902 hasBorder = hasBorder !== undefined ? !!hasBorder : !this.hasBorder();
903
904 this.border = !!hasBorder;
905 };
906
907 /**
908 * Toggle the default size flag of the image
909 *
910 * @param {boolean} [isDefault] Default size flag. Omit to toggle current value.
911 * @fires ve.dm.MWImageModel#sizeDefaultChange
912 */
913 ve.dm.MWImageModel.prototype.toggleDefaultSize = function ( isDefault ) {
914 isDefault = isDefault !== undefined ? !!isDefault : !this.isDefaultSize();
915
916 if ( this.isDefaultSize() !== isDefault ) {
917 this.scalable.toggleDefault( !!isDefault );
918 this.resetDefaultDimensions();
919 this.emit( 'sizeDefaultChange', !!isDefault );
920 }
921 };
922
923 /**
924 * Cache all image attributes
925 *
926 * @param {Object} attrs Image attributes
927 */
928 ve.dm.MWImageModel.prototype.cacheOriginalImageAttributes = function ( attrs ) {
929 this.attributesCache = attrs;
930 };
931
932 /**
933 * Get the cache of all image attributes
934 *
935 * @return {Object} attrs Image attributes
936 */
937 ve.dm.MWImageModel.prototype.getOriginalImageAttributes = function () {
938 return this.attributesCache;
939 };
940
941 /**
942 * Set the current dimensions of the image.
943 * Normalize in case only one dimension is available.
944 *
945 * @param {Object} dimensions Dimensions width and height
946 * @param {number} dimensions.width The width of the image
947 * @param {number} dimensions.height The height of the image
948 */
949 ve.dm.MWImageModel.prototype.setCurrentDimensions = function ( dimensions ) {
950 const normalizedDimensions = ve.dm.Scalable.static.getDimensionsFromValue( dimensions, this.scalable.getRatio() );
951 this.scalable.setCurrentDimensions( normalizedDimensions );
952 };
953
954 /**
955 * Set alternate text
956 *
957 * @param {string} text Alternate text
958 */
959 ve.dm.MWImageModel.prototype.setAltText = function ( text ) {
960 this.altText = text;
961 };
962
963 /**
964 * Set image type
965 *
966 * @see #getType
967 *
968 * @param {string} type Image type
969 * @fires ve.dm.MWImageModel#typeChange
970 */
971 ve.dm.MWImageModel.prototype.setType = function ( type ) {
972 const isDefaultAligned = this.isDefaultAligned( this.imageCurrentType );
973
974 this.type = type;
975
976 // If we're switching between inline and block or vice versa,
977 // check if the old type image was default aligned
978 if ( isDefaultAligned && this.imageCurrentType !== this.type ) {
979 if ( this.type === 'none' || this.type === 'frameless' ) {
980 // Reset default alignment for switching to inline images
981 this.setAlignment( 'none' );
982 } else {
983 // Reset default alignment for all other images
984 this.setAlignment( 'default' );
985 }
986 }
987
988 // Cache the current type for next check
989 this.imageCurrentType = type;
990
991 if ( type === 'frame' || type === 'thumb' ) {
992 // Disable border option
993 this.toggleBorderable( false );
994 } else {
995 // Enable border option
996 this.toggleBorderable( true );
997 }
998
999 // If type is frame, set to 'default' size
1000 if ( type === 'frame' ) {
1001 this.toggleDefaultSize( true );
1002 }
1003
1004 // Let the image node update scalable considerations
1005 // for default and max dimensions as per the new type.
1006 ve.dm.MWImageNode.static.syncScalableToType( type, this.getMediaType(), this.getScalable() );
1007
1008 this.emit( 'typeChange', type );
1009 };
1010
1011 /**
1012 * Reset the default dimensions of the image based on its type
1013 * and on whether we have the originalDimensions object from
1014 * the API
1015 */
1016 ve.dm.MWImageModel.prototype.resetDefaultDimensions = function () {
1017 const originalDimensions = this.scalable.getOriginalDimensions();
1018
1019 if ( !ve.isEmptyObject( originalDimensions ) ) {
1020 if ( this.getType() === 'thumb' || this.getType() === 'frameless' ) {
1021 // Default is thumb size
1022 if ( originalDimensions.width <= this.defaultThumbSize ) {
1023 this.scalable.setDefaultDimensions( originalDimensions );
1024 } else {
1025 this.scalable.setDefaultDimensions(
1026 ve.dm.Scalable.static.getDimensionsFromValue( {
1027 width: this.defaultThumbSize
1028 }, this.scalable.getRatio() )
1029 );
1030 }
1031 } else {
1032 // Default is original size
1033 this.scalable.setDefaultDimensions( originalDimensions );
1034 }
1035 } else {
1036 this.scalable.clearDefaultDimensions();
1037 }
1038 };
1039
1040 /**
1041 * Retrieve the currently set default dimensions from the scalable
1042 * object attached to the image.
1043 *
1044 * @return {Object} Image default dimensions
1045 */
1046 ve.dm.MWImageModel.prototype.getDefaultDimensions = function () {
1047 return this.scalable.getDefaultDimensions();
1048 };
1049
1050 /**
1051 * Change size type of the image
1052 *
1053 * @param {string} type Size type 'default', 'custom' or 'scale'
1054 */
1055 ve.dm.MWImageModel.prototype.setSizeType = function ( type ) {
1056 if ( this.sizeType !== type ) {
1057 this.sizeType = type;
1058 this.toggleDefaultSize( type === 'default' );
1059 }
1060 };
1061
1062 /**
1063 * Set image alignment
1064 *
1065 * @see #getAlignment
1066 *
1067 * @param {string} align Alignment
1068 * @fires ve.dm.MWImageModel#alignmentChange
1069 */
1070 ve.dm.MWImageModel.prototype.setAlignment = function ( align ) {
1071 if ( align === 'default' ) {
1072 // If default, set the alignment to language dir default
1073 align = this.getDefaultDir();
1074 }
1075
1076 this.alignment = align;
1077 this.emit( 'alignmentChange', align );
1078 };
1079
1080 /**
1081 * Set image vertical alignment
1082 *
1083 * @see #getVerticalAlignment
1084 *
1085 * @param {string} valign Alignment
1086 * @fires ve.dm.MWImageModel#alignmentChange
1087 */
1088 ve.dm.MWImageModel.prototype.setVerticalAlignment = function ( valign ) {
1089 this.verticalAlignment = valign;
1090 this.emit( 'alignmentChange', valign );
1091 };
1092
1093 /**
1094 * Get the default alignment according to the document direction
1095 *
1096 * @param {string} [imageNodeType] Optional. The image node type that we would
1097 * like to get the default direction for. Supplying this parameter allows us
1098 * to check what the default alignment of a specific type of node would be.
1099 * If the parameter is not supplied, the default alignment will be calculated
1100 * based on the current node type.
1101 * @return {string} Node alignment based on document direction
1102 */
1103 ve.dm.MWImageModel.prototype.getDefaultDir = function ( imageNodeType ) {
1104 imageNodeType = imageNodeType || this.getImageNodeType();
1105
1106 if ( this.parentDoc.getDir() === 'rtl' ) {
1107 // Assume position is 'left'
1108 return ( imageNodeType === 'mwBlockImage' ) ? 'left' : 'none';
1109 } else {
1110 // Assume position is 'right'
1111 return ( imageNodeType === 'mwBlockImage' ) ? 'right' : 'none';
1112 }
1113 };
1114
1115 /**
1116 * Get the image file source
1117 * The image file source that points to the location of the
1118 * file on the Web.
1119 * For instance, '//upload.wikimedia.org/wikipedia/commons/0/0f/Foo.jpg'
1120 *
1121 * @return {string} The source of the given media file
1122 */
1123 ve.dm.MWImageModel.prototype.getImageSource = function () {
1124 return this.imageSrc;
1125 };
1126
1127 /**
1128 * Get the image file resource name.
1129 * The resource name represents the filename without the full
1130 * source url.
1131 * For example, './File:Foo.jpg'
1132 *
1133 * @return {string} The resource name of the given media file
1134 */
1135 ve.dm.MWImageModel.prototype.getImageResourceName = function () {
1136 return this.imageResourceName;
1137 };
1138
1139 /**
1140 * Get the image href value.
1141 * This is the link that the image leads to. It usually contains
1142 * the link to the source of the image in commons or locally, but
1143 * may hold an alternative link if link= is supplied in the wikitext.
1144 * For example, './File:Foo.jpg' or 'http://www.wikipedia.org'
1145 *
1146 * @return {string} The destination href of the given media file
1147 */
1148 ve.dm.MWImageModel.prototype.getImageHref = function () {
1149 return this.imageHref;
1150 };
1151
1152 /**
1153 * @param {string|null} classAttr
1154 */
1155 ve.dm.MWImageModel.prototype.setImageClassAttr = function ( classAttr ) {
1156 this.imageClassAttr = classAttr;
1157 };
1158
1159 /**
1160 * @return {string|null}
1161 */
1162 ve.dm.MWImageModel.prototype.getImageClassAttr = function () {
1163 return this.imageClassAttr;
1164 };
1165
1166 /**
1167 * @param {string|null} classAttr
1168 */
1169 ve.dm.MWImageModel.prototype.setImgWrapperClassAttr = function ( classAttr ) {
1170 this.imgWrapperClassAttr = classAttr;
1171 };
1172
1173 /**
1174 * @return {string|null}
1175 */
1176 ve.dm.MWImageModel.prototype.getImgWrapperClassAttr = function () {
1177 return this.imgWrapperClassAttr;
1178 };
1179
1180 /**
1181 * Attach a new scalable object to the model and request the
1182 * information from the API.
1183 *
1184 * @param {ve.dm.Scalable} scalable
1185 */
1186 ve.dm.MWImageModel.prototype.attachScalable = function ( scalable ) {
1187 const imageName = mw.libs.ve.normalizeParsoidResourceName( this.getResourceName() );
1188
1189 if ( this.scalable instanceof ve.dm.Scalable ) {
1190 this.scalable.disconnect( this );
1191 }
1192 this.scalable = scalable;
1193
1194 // Events
1195 this.scalable.connect( this, { defaultSizeChange: 'onScalableDefaultSizeChange' } );
1196
1197 // Call for updated scalable
1198 if ( imageName ) {
1199 ve.dm.MWImageNode.static.getScalablePromise( imageName ).done( ( info ) => {
1200 this.scalable.setOriginalDimensions( {
1201 width: info.width,
1202 height: info.height
1203 } );
1204 // Update media type
1205 this.setMediaType( info.mediatype );
1206 // Update according to type
1207 ve.dm.MWImageNode.static.syncScalableToType(
1208 this.getType(),
1209 this.getMediaType(),
1210 this.getScalable()
1211 );
1212
1213 // We have to adjust the details in the initial hash if the original
1214 // image was 'default' since we didn't have default until now and the
1215 // default dimensions that were 'recorded' were wrong
1216 if ( !ve.isEmptyObject( this.initialHash ) && this.initialHash.scalable.isDefault ) {
1217 this.initialHash.scalable.currentDimensions = this.scalable.getDefaultDimensions();
1218 }
1219
1220 } );
1221 }
1222 };
1223
1224 /**
1225 * Set the filename of the current image
1226 *
1227 * @param {string} filename Image filename (without namespace)
1228 */
1229 ve.dm.MWImageModel.prototype.setFilename = function ( filename ) {
1230 this.filename = filename;
1231 };
1232
1233 /**
1234 * Get the filename of the current image
1235 *
1236 * @return {string} filename Image filename (without namespace)
1237 */
1238 ve.dm.MWImageModel.prototype.getFilename = function () {
1239 return this.filename;
1240 };
1241
1242 /**
1243 * If the image changed, update scalable definitions.
1244 *
1245 * @param {Object} originalDimensions Image original dimensions
1246 */
1247 ve.dm.MWImageModel.prototype.updateScalableDetails = function ( originalDimensions ) {
1248 let newDimensions;
1249
1250 // Resize the new image's current dimensions to default or based on the bounding box
1251 if ( this.isDefaultSize() ) {
1252 // Scale to default
1253 newDimensions = ve.dm.MWImageNode.static.scaleToThumbnailSize( originalDimensions );
1254 } else {
1255 if ( this.getBoundingBox() ) {
1256 // Scale the new image by its width
1257 newDimensions = ve.dm.MWImageNode.static.resizeToBoundingBox(
1258 originalDimensions,
1259 {
1260 width: this.boundingBox.width,
1261 height: Infinity
1262 }
1263 );
1264 } else {
1265 newDimensions = originalDimensions;
1266 }
1267 }
1268
1269 if ( newDimensions ) {
1270 this.getScalable().setCurrentDimensions( newDimensions );
1271 }
1272 };
1273
1274 /**
1275 * Set image caption document.
1276 *
1277 * @param {ve.dm.Document} doc Image caption document
1278 */
1279 ve.dm.MWImageModel.prototype.setCaptionDocument = function ( doc ) {
1280 this.captionDoc = doc;
1281 };
1282
1283 /**
1284 * Check if the model attributes and parameters have been modified by
1285 * comparing the current hash to the new hash object.
1286 *
1287 * @return {boolean} Model has been modified
1288 */
1289 ve.dm.MWImageModel.prototype.hasBeenModified = function () {
1290 if ( this.initialHash ) {
1291 return !ve.compare( this.initialHash, this.getHashObject() );
1292 }
1293 return true;
1294 };