utils.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 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. }
  55. /**
  56. * {@link module:engine/view/matcher~Matcher} pattern. Checks if given element is `figcaption` element and is placed
  57. * inside image `figure` element.
  58. *
  59. * @param {module:engine/view/element~Element} element
  60. * @returns {Object|null} Returns object accepted by {@link module:engine/view/matcher~Matcher} or `null` if element
  61. * cannot be matched.
  62. */
  63. export function matchImageCaption( element ) {
  64. const parent = element.parent;
  65. // Convert only captions for images.
  66. if ( element.name == 'figcaption' && parent && parent.name == 'figure' && parent.hasClass( 'image' ) ) {
  67. return { name: true };
  68. }
  69. return null;
  70. }