UNPKG

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