8
0

utils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module upload/utils
  7. */
  8. import ModelPosition from '@ckeditor/ckeditor5-engine/src/model/position';
  9. /**
  10. * Checks if given file is an image.
  11. *
  12. * @param {File} file
  13. * @returns {Boolean}
  14. */
  15. export function isImageType( file ) {
  16. const types = /^image\/(jpeg|png|gif|bmp)$/;
  17. return types.test( file.type );
  18. }
  19. /**
  20. * Returns a model position which is optimal (in terms of UX) for inserting an image.
  21. *
  22. * For instance, if a selection is in a middle of a paragraph, position before this paragraph
  23. * will be returned, so that it's not split. If the selection is at the end of a paragraph,
  24. * position after this paragraph will be returned.
  25. *
  26. * Note: If selection is placed in an empty block, that block will be returned. If that position
  27. * is then passed to {@link module:engine/controller/datacontroller~DataController#insertContent}
  28. * that block will be fully replaced by the image.
  29. *
  30. * @param {module:engine/model/selection~Selection} selection Selection based on which the
  31. * insertion position should be calculated.
  32. * @returns {module:engine/model/position~Position} The optimal position.
  33. */
  34. export function findOptimalInsertionPosition( selection ) {
  35. const selectedElement = selection.getSelectedElement();
  36. if ( selectedElement ) {
  37. return ModelPosition.createAfter( selectedElement );
  38. }
  39. const firstBlock = selection.getSelectedBlocks().next().value;
  40. if ( firstBlock ) {
  41. // If inserting into an empty block – return position in that block. It will get
  42. // replaced with the image by insertContent(). #42.
  43. if ( firstBlock.isEmpty ) {
  44. return ModelPosition.createAt( firstBlock );
  45. }
  46. const positionAfter = ModelPosition.createAfter( firstBlock );
  47. // If selection is at the end of the block - return position after the block.
  48. if ( selection.focus.isTouching( positionAfter ) ) {
  49. return positionAfter;
  50. }
  51. // Otherwise return position before the block.
  52. return ModelPosition.createBefore( firstBlock );
  53. }
  54. return selection.focus;
  55. }