utils.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module table/utils
  7. */
  8. import { isWidget, toWidget } from '@ckeditor/ckeditor5-widget/src/utils';
  9. import { findAncestor } from './commands/utils';
  10. /**
  11. * Converts a given {@link module:engine/view/element~Element} to a table widget:
  12. * * Adds a {@link module:engine/view/element~Element#_setCustomProperty custom property} allowing to recognize the table widget element.
  13. * * Calls the {@link module:widget/utils~toWidget} function with the proper element's label creator.
  14. *
  15. * @param {module:engine/view/element~Element} viewElement
  16. * @param {module:engine/view/downcastwriter~DowncastWriter} writer An instance of the view writer.
  17. * @param {String} label The element's label. It will be concatenated with the table `alt` attribute if one is present.
  18. * @returns {module:engine/view/element~Element}
  19. */
  20. export function toTableWidget( viewElement, writer ) {
  21. writer.setCustomProperty( 'table', true, viewElement );
  22. return toWidget( viewElement, writer, { hasSelectionHandler: true } );
  23. }
  24. /**
  25. * Checks if a given view element is a table widget.
  26. *
  27. * @param {module:engine/view/element~Element} viewElement
  28. * @returns {Boolean}
  29. */
  30. export function isTableWidget( viewElement ) {
  31. return !!viewElement.getCustomProperty( 'table' ) && isWidget( viewElement );
  32. }
  33. /**
  34. * Returns a table widget editing view element if one is selected.
  35. *
  36. * @param {module:engine/view/selection~Selection|module:engine/view/documentselection~DocumentSelection} selection
  37. * @returns {module:engine/view/element~Element|null}
  38. */
  39. export function getSelectedTableWidget( selection ) {
  40. const viewElement = selection.getSelectedElement();
  41. if ( viewElement && isTableWidget( viewElement ) ) {
  42. return viewElement;
  43. }
  44. return null;
  45. }
  46. /**
  47. * Returns a table widget editing view element if one is among selection's ancestors.
  48. *
  49. * @param {module:engine/view/selection~Selection|module:engine/view/documentselection~DocumentSelection} selection
  50. * @returns {module:engine/view/element~Element|null}
  51. */
  52. export function getTableWidgetAncestor( selection ) {
  53. const parentTable = findAncestor( 'table', selection.getFirstPosition() );
  54. if ( parentTable && isTableWidget( parentTable.parent ) ) {
  55. return parentTable.parent;
  56. }
  57. return null;
  58. }