utils.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module table/commands/utils
  7. */
  8. /**
  9. * Returns the parent element of given name. Returns undefined if position is not inside desired parent.
  10. *
  11. * @param {String} parentName Name of parent element to find.
  12. * @param {module:engine/model/position~Position|module:engine/model/position~Position} position Position to start searching.
  13. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
  14. */
  15. export function findAncestor( parentName, position ) {
  16. let parent = position.parent;
  17. while ( parent ) {
  18. if ( parent.name === parentName ) {
  19. return parent;
  20. }
  21. parent = parent.parent;
  22. }
  23. }
  24. /**
  25. * A common method to update the numeric value. If a value is the default one, it will be unset.
  26. *
  27. * @param {String} key Attribute key.
  28. * @param {*} value The new attribute value.
  29. * @param {module:engine/model/item~Item} item Model item on which the attribute will be set.
  30. * @param {module:engine/model/writer~Writer} writer
  31. * @param {*} defaultValue Default attribute value. If a value is lower or equal, it will be unset.
  32. */
  33. export function updateNumericAttribute( key, value, item, writer, defaultValue = 1 ) {
  34. if ( value > defaultValue ) {
  35. writer.setAttribute( key, value, item );
  36. } else {
  37. writer.removeAttribute( key, item );
  38. }
  39. }
  40. /**
  41. * Common method to create empty table cell - it will create proper model structure as table cell must have at least one block inside.
  42. *
  43. * @param {module:engine/model/writer~Writer} writer Model writer.
  44. * @param {module:engine/model/position~Position} insertPosition Position at which table cell should be inserted.
  45. * @param {Object} attributes Element's attributes.
  46. */
  47. export function createEmptyTableCell( writer, insertPosition, attributes = {} ) {
  48. const tableCell = writer.createElement( 'tableCell', attributes );
  49. writer.insertElement( 'paragraph', tableCell );
  50. writer.insert( tableCell, insertPosition );
  51. }