UNPKG

2.36 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4 */
5
6/**
7 * @module image/imagecaptionutils/utils
8 */
9
10import { Plugin } from 'ckeditor5/src/core';
11
12import ImageUtils from '../imageutils';
13
14/**
15 * The image caption utilities plugin.
16 *
17 * @extends module:core/plugin~Plugin
18 */
19export default class ImageCaptionUtils extends Plugin {
20 /**
21 * @inheritDoc
22 */
23 static get pluginName() {
24 return 'ImageCaptionUtils';
25 }
26
27 /**
28 * @inheritDoc
29 */
30 static get requires() {
31 return [ ImageUtils ];
32 }
33
34 /**
35 * Returns the caption model element from a given image element. Returns `null` if no caption is found.
36 *
37 * @param {module:engine/model/element~Element} imageModelElement
38 * @returns {module:engine/model/element~Element|null}
39 */
40 getCaptionFromImageModelElement( imageModelElement ) {
41 for ( const node of imageModelElement.getChildren() ) {
42 if ( !!node && node.is( 'element', 'caption' ) ) {
43 return node;
44 }
45 }
46
47 return null;
48 }
49
50 /**
51 * Returns the caption model element for a model selection. Returns `null` if the selection has no caption element ancestor.
52 *
53 * @param {module:engine/model/selection~Selection} selection
54 * @returns {module:engine/model/element~Element|null}
55 */
56 getCaptionFromModelSelection( selection ) {
57 const imageUtils = this.editor.plugins.get( 'ImageUtils' );
58 const captionElement = selection.getFirstPosition().findAncestor( 'caption' );
59
60 if ( !captionElement ) {
61 return null;
62 }
63
64 if ( imageUtils.isBlockImage( captionElement.parent ) ) {
65 return captionElement;
66 }
67
68 return null;
69 }
70
71 /**
72 * {@link module:engine/view/matcher~Matcher} pattern. Checks if a given element is a `<figcaption>` element that is placed
73 * inside the image `<figure>` element.
74 *
75 * @param {module:engine/view/element~Element} element
76 * @returns {Object|null} Returns the object accepted by {@link module:engine/view/matcher~Matcher} or `null` if the element
77 * cannot be matched.
78 */
79 matchImageCaptionViewElement( element ) {
80 const imageUtils = this.editor.plugins.get( 'ImageUtils' );
81
82 // Convert only captions for images.
83 if ( element.name == 'figcaption' && imageUtils.isBlockImageView( element.parent ) ) {
84 return { name: true };
85 }
86
87 return null;
88 }
89}