utils.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module image/imagecaption/utils
  7. */
  8. import ViewEditableElement from '@ckeditor/ckeditor5-engine/src/view/editableelement';
  9. import ModelElement from '@ckeditor/ckeditor5-engine/src/model/element';
  10. const captionSymbol = Symbol( 'imageCaption' );
  11. /**
  12. * Returns a function that creates caption editable element for the given {@link module:engine/view/document~Document}.
  13. *
  14. * @param {module:engine/view/document~Document} viewDocument
  15. * @return {Function}
  16. */
  17. export function captionElementCreator( viewDocument ) {
  18. return () => {
  19. const editable = new ViewEditableElement( 'figcaption', { contenteditable: true } );
  20. editable.document = viewDocument;
  21. editable.setCustomProperty( captionSymbol, true );
  22. editable.on( 'change:isFocused', ( evt, property, is ) => {
  23. if ( is ) {
  24. editable.addClass( 'focused' );
  25. } else {
  26. editable.removeClass( 'focused' );
  27. }
  28. } );
  29. return editable;
  30. };
  31. }
  32. /**
  33. * Returns `true` if given view element is image's caption editable.
  34. *
  35. * @param {module:engine/view/element~Element} viewElement
  36. * @return {Boolean}
  37. */
  38. export function isCaption( viewElement ) {
  39. return !!viewElement.getCustomProperty( captionSymbol );
  40. }
  41. /**
  42. * Returns caption's model element from given image element. Returns `null` if no caption is found.
  43. *
  44. * @param {module:engine/model/element~Element} imageModelElement
  45. * @return {module:engine/model/element~Element|null}
  46. */
  47. export function getCaptionFromImage( imageModelElement ) {
  48. for ( let node of imageModelElement.getChildren() ) {
  49. if ( node instanceof ModelElement && node.name == 'caption' ) {
  50. return node;
  51. }
  52. }
  53. return null;
  54. }