editableuiview.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module ui/editableui/editableuiview
  7. */
  8. import View from '../view';
  9. import Template from '../template';
  10. /**
  11. * The editable UI view class.
  12. *
  13. * @extends module:ui/view~View
  14. */
  15. export default class EditableUIView extends View {
  16. /**
  17. * Creates an instance of EditableUIView class.
  18. *
  19. * @param {module:utils/locale~Locale} [locale] The locale instance.
  20. * @param {HTMLElement} [editableElement] The editable element. If not specified, this view
  21. * should create it. Otherwise, the existing element should be used.
  22. */
  23. constructor( locale, editableElement ) {
  24. super( locale );
  25. const bind = this.bindTemplate;
  26. if ( editableElement ) {
  27. this.element = this.editableElement = editableElement;
  28. }
  29. this.template = new Template( {
  30. tag: 'div',
  31. attributes: {
  32. class: [
  33. bind.to( 'isFocused', value => value ? 'ck-focused' : 'ck-blurred' ),
  34. 'ck-editor__editable'
  35. ],
  36. contenteditable: bind.to( 'isReadOnly', value => !value ),
  37. }
  38. } );
  39. /**
  40. * Controls whether the editable is writable or not.
  41. *
  42. * @observable
  43. * @member {Boolean} #isReadOnly
  44. */
  45. this.set( 'isReadOnly', false );
  46. /**
  47. * Controls whether the editable is focused, i.e. the user is typing in it.
  48. *
  49. * @observable
  50. * @member {Boolean} #isFocused
  51. */
  52. this.set( 'isFocused', false );
  53. /**
  54. * An external {@link #editableElement} passed into the constructor, which also means
  55. * the view will not render its {@link #template}.
  56. *
  57. * @member {HTMLElement} #externalElement
  58. */
  59. this.externalElement = editableElement;
  60. /**
  61. * The element which is the main editable element (usually the one with `contentEditable="true"`).
  62. *
  63. * @readonly
  64. * @member {HTMLElement} #editableElement
  65. */
  66. }
  67. /**
  68. * Initializes the view by either applying the {@link #template} to the existing
  69. * {@link #editableElement} or assigning {@link #element} as {@link #editableElement}.
  70. */
  71. init() {
  72. if ( this.externalElement ) {
  73. this.template.apply( this.externalElement );
  74. } else {
  75. this.editableElement = this.element;
  76. }
  77. super.init();
  78. }
  79. /**
  80. * @inheritDoc
  81. */
  82. destroy() {
  83. if ( this.externalElement ) {
  84. this.template.revert( this.externalElement );
  85. }
  86. super.destroy();
  87. }
  88. }