utils.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module image/imagecaption/utils
  7. */
  8. import ModelElement from '@ckeditor/ckeditor5-engine/src/model/element';
  9. import { attachPlaceholder } from '@ckeditor/ckeditor5-engine/src/view/placeholder';
  10. import { toWidgetEditable } from '@ckeditor/ckeditor5-widget/src/utils';
  11. const captionSymbol = Symbol( 'imageCaption' );
  12. /**
  13. * Returns a function that creates a caption editable element for the given {@link module:engine/view/document~Document}.
  14. *
  15. * @param {module:engine/view/view~View} view
  16. * @param {String} placeholderText The text to be displayed when the caption is empty.
  17. * @return {Function}
  18. */
  19. export function captionElementCreator( view, placeholderText ) {
  20. return writer => {
  21. const editable = writer.createEditableElement( 'figcaption' );
  22. writer.setCustomProperty( captionSymbol, true, editable );
  23. attachPlaceholder( view, editable, placeholderText );
  24. return toWidgetEditable( editable, writer );
  25. };
  26. }
  27. /**
  28. * Returns `true` if a given view element is the image caption editable.
  29. *
  30. * @param {module:engine/view/element~Element} viewElement
  31. * @return {Boolean}
  32. */
  33. export function isCaption( viewElement ) {
  34. return !!viewElement.getCustomProperty( captionSymbol );
  35. }
  36. /**
  37. * Returns the caption model element from a given image element. Returns `null` if no caption is found.
  38. *
  39. * @param {module:engine/model/element~Element} imageModelElement
  40. * @return {module:engine/model/element~Element|null}
  41. */
  42. export function getCaptionFromImage( imageModelElement ) {
  43. for ( const node of imageModelElement.getChildren() ) {
  44. if ( node instanceof ModelElement && node.name == 'caption' ) {
  45. return node;
  46. }
  47. }
  48. return null;
  49. }
  50. /**
  51. * {@link module:engine/view/matcher~Matcher} pattern. Checks if a given element is a `<figcaption>` element that is placed
  52. * inside the image `<figure>` element.
  53. *
  54. * @param {module:engine/view/element~Element} element
  55. * @returns {Object|null} Returns the object accepted by {@link module:engine/view/matcher~Matcher} or `null` if the element
  56. * cannot be matched.
  57. */
  58. export function matchImageCaption( element ) {
  59. const parent = element.parent;
  60. // Convert only captions for images.
  61. if ( element.name == 'figcaption' && parent && parent.name == 'figure' && parent.hasClass( 'image' ) ) {
  62. return { name: true };
  63. }
  64. return null;
  65. }