decouplededitor.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module editor-decoupled/decouplededitor
  7. */
  8. import Editor from '@ckeditor/ckeditor5-core/src/editor/editor';
  9. import DataApiMixin from '@ckeditor/ckeditor5-core/src/editor/utils/dataapimixin';
  10. import HtmlDataProcessor from '@ckeditor/ckeditor5-engine/src/dataprocessor/htmldataprocessor';
  11. import DecoupledEditorUI from './decouplededitorui';
  12. import DecoupledEditorUIView from './decouplededitoruiview';
  13. import getDataFromElement from '@ckeditor/ckeditor5-utils/src/dom/getdatafromelement';
  14. import setDataInElement from '@ckeditor/ckeditor5-utils/src/dom/setdatainelement';
  15. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  16. import { isElement } from 'lodash-es';
  17. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  18. import secureSourceElement from '@ckeditor/ckeditor5-core/src/editor/utils/securesourceelement';
  19. /**
  20. * The {@glink builds/guides/overview#document-editor decoupled editor} implementation.
  21. * It provides an inline editable and a toolbar. However, unlike other editors,
  22. * it does not render these components anywhere in the DOM unless configured.
  23. *
  24. * This type of an editor is dedicated to integrations which require a customized UI with an open
  25. * structure, allowing developers to specify the exact location of the interface.
  26. *
  27. * See the document editor {@glink examples/builds/document-editor demo} to learn about possible use cases
  28. * for the decoupled editor.
  29. *
  30. * In order to create a decoupled editor instance, use the static
  31. * {@link module:editor-decoupled/decouplededitor~DecoupledEditor.create `DecoupledEditor.create()`} method.
  32. *
  33. * # Decoupled editor and document editor build
  34. *
  35. * The decoupled editor can be used directly from source (if you installed the
  36. * [`@ckeditor/ckeditor5-editor-decoupled`](https://www.npmjs.com/package/@ckeditor/ckeditor5-editor-decoupled) package)
  37. * but it is also available in the {@glink builds/guides/overview#document-editor document editor build}.
  38. *
  39. * {@glink builds/guides/overview Builds} are ready-to-use editors with plugins bundled in. When using the editor from
  40. * source you need to take care of loading all plugins by yourself
  41. * (through the {@link module:core/editor/editorconfig~EditorConfig#plugins `config.plugins`} option).
  42. * Using the editor from source gives much better flexibility and allows for easier customization.
  43. *
  44. * Read more about initializing the editor from source or as a build in
  45. * {@link module:editor-decoupled/decouplededitor~DecoupledEditor.create `DecoupledEditor.create()`}.
  46. *
  47. * @mixes module:core/editor/utils/dataapimixin~DataApiMixin
  48. * @implements module:core/editor/editorwithui~EditorWithUI
  49. * @extends module:core/editor/editor~Editor
  50. */
  51. export default class DecoupledEditor extends Editor {
  52. /**
  53. * Creates an instance of the decoupled editor.
  54. *
  55. * **Note:** Do not use the constructor to create editor instances. Use the static
  56. * {@link module:editor-decoupled/decouplededitor~DecoupledEditor.create `DecoupledEditor.create()`} method instead.
  57. *
  58. * @protected
  59. * @param {HTMLElement|String} sourceElementOrData The DOM element that will be the source for the created editor
  60. * (on which the editor will be initialized) or initial data for the editor. For more information see
  61. * {@link module:editor-balloon/ballooneditor~BalloonEditor.create `BalloonEditor.create()`}.
  62. * @param {module:core/editor/editorconfig~EditorConfig} config The editor configuration.
  63. */
  64. constructor( sourceElementOrData, config ) {
  65. super( config );
  66. if ( isElement( sourceElementOrData ) ) {
  67. this.sourceElement = sourceElementOrData;
  68. secureSourceElement( this );
  69. }
  70. this.data.processor = new HtmlDataProcessor( this.data.viewDocument );
  71. this.model.document.createRoot();
  72. const shouldToolbarGroupWhenFull = !this.config.get( 'toolbar.shouldNotGroupWhenFull' );
  73. const view = new DecoupledEditorUIView( this.locale, this.editing.view, {
  74. editableElement: this.sourceElement,
  75. shouldToolbarGroupWhenFull
  76. } );
  77. this.ui = new DecoupledEditorUI( this, view );
  78. }
  79. /**
  80. * Destroys the editor instance, releasing all resources used by it.
  81. *
  82. * **Note**: The decoupled editor does not remove the toolbar and editable when destroyed. You can
  83. * do that yourself in the destruction chain:
  84. *
  85. * editor.destroy()
  86. * .then( () => {
  87. * // Remove the toolbar from DOM.
  88. * editor.ui.view.toolbar.element.remove();
  89. *
  90. * // Remove the editable from DOM.
  91. * editor.ui.view.editable.element.remove();
  92. *
  93. * console.log( 'Editor was destroyed' );
  94. * } );
  95. *
  96. * @returns {Promise}
  97. */
  98. destroy() {
  99. // Cache the data, then destroy.
  100. // It's safe to assume that the model->view conversion will not work after super.destroy().
  101. const data = this.getData();
  102. this.ui.destroy();
  103. return super.destroy()
  104. .then( () => {
  105. if ( this.sourceElement ) {
  106. setDataInElement( this.sourceElement, data );
  107. }
  108. } );
  109. }
  110. /**
  111. * Creates a new decoupled editor instance.
  112. *
  113. * Remember that `DecoupledEditor` does not append the toolbar element to your web page so you have to do it manually after the editor
  114. * has been initialized.
  115. *
  116. * There are two ways how the editor can be initialized.
  117. *
  118. * # Using an existing DOM element (and loading data from it)
  119. *
  120. * You can initialize the editor using an existing DOM element:
  121. *
  122. * DecoupledEditor
  123. * .create( document.querySelector( '#editor' ) )
  124. * .then( editor => {
  125. * console.log( 'Editor was initialized', editor );
  126. *
  127. * // Append the toolbar to the <body> element.
  128. * document.body.appendChild( editor.ui.view.toolbar.element );
  129. * } )
  130. * .catch( err => {
  131. * console.error( err.stack );
  132. * } );
  133. *
  134. * The element's content will be used as the editor data and the element will become the editable element.
  135. *
  136. * # Creating a detached editor
  137. *
  138. * Alternatively, you can initialize the editor by passing the initial data directly as a string.
  139. * In this case, you will have to manually append both the toolbar element and the editable element to your web page.
  140. *
  141. * DecoupledEditor
  142. * .create( '<p>Hello world!</p>' )
  143. * .then( editor => {
  144. * console.log( 'Editor was initialized', editor );
  145. *
  146. * // Append the toolbar to the <body> element.
  147. * document.body.appendChild( editor.ui.view.toolbar.element );
  148. *
  149. * // Initial data was provided so the editor UI element needs to be added manually to the DOM.
  150. * document.body.appendChild( editor.ui.getEditableElement() );
  151. * } )
  152. * .catch( err => {
  153. * console.error( err.stack );
  154. * } );
  155. *
  156. * This lets you dynamically append the editor to your web page whenever it is convenient for you. You may use this method if your
  157. * web page content is generated on the client side and the DOM structure is not ready at the moment when you initialize the editor.
  158. *
  159. * # Using an existing DOM element (and data provided in `config.initialData`)
  160. *
  161. * You can also mix these two ways by providing a DOM element to be used and passing the initial data through the configuration:
  162. *
  163. * DecoupledEditor
  164. * .create( document.querySelector( '#editor' ), {
  165. * initialData: '<h2>Initial data</h2><p>Foo bar.</p>'
  166. * } )
  167. * .then( editor => {
  168. * console.log( 'Editor was initialized', editor );
  169. *
  170. * // Append the toolbar to the <body> element.
  171. * document.body.appendChild( editor.ui.view.toolbar.element );
  172. * } )
  173. * .catch( err => {
  174. * console.error( err.stack );
  175. * } );
  176. *
  177. * This method can be used to initialize the editor on an existing element with the specified content in case if your integration
  178. * makes it difficult to set the content of the source element.
  179. *
  180. * Note that an error will be thrown if you pass the initial data both as the first parameter and also in the configuration.
  181. *
  182. * # Configuring the editor
  183. *
  184. * See the {@link module:core/editor/editorconfig~EditorConfig editor configuration documentation} to learn more about
  185. * customizing plugins, toolbar and more.
  186. *
  187. * # Using the editor from source
  188. *
  189. * The code samples listed in the previous sections of this documentation assume that you are using an
  190. * {@glink builds/guides/overview editor build} (for example – `@ckeditor/ckeditor5-build-decoupled`).
  191. *
  192. * If you want to use the decoupled editor from source (`@ckeditor/ckeditor5-editor-decoupled/src/decouplededitor`),
  193. * you need to define the list of
  194. * {@link module:core/editor/editorconfig~EditorConfig#plugins plugins to be initialized} and
  195. * {@link module:core/editor/editorconfig~EditorConfig#toolbar toolbar items}. Read more about using the editor from
  196. * source in the {@glink builds/guides/integration/advanced-setup "Advanced setup" guide}.
  197. *
  198. * @param {HTMLElement|String} sourceElementOrData The DOM element that will be the source for the created editor
  199. * or the editor's initial data.
  200. *
  201. * If a DOM element is passed, its content will be automatically loaded to the editor upon initialization.
  202. * Moreover, the editor data will be set back to the original element once the editor is destroyed.
  203. *
  204. * If the initial data is passed, a detached editor will be created. In this case you need to insert it into the DOM manually.
  205. * It is available via
  206. * {@link module:editor-decoupled/decouplededitorui~DecoupledEditorUI#getEditableElement `editor.ui.getEditableElement()`}.
  207. *
  208. * @param {module:core/editor/editorconfig~EditorConfig} [config] The editor configuration.
  209. * @returns {Promise} A promise resolved once the editor is ready. The promise resolves with the created editor instance.
  210. */
  211. static create( sourceElementOrData, config = {} ) {
  212. return new Promise( resolve => {
  213. const isHTMLElement = isElement( sourceElementOrData );
  214. if ( isHTMLElement && sourceElementOrData.tagName === 'TEXTAREA' ) {
  215. // Documented in core/editor/editor.js
  216. throw new CKEditorError(
  217. 'editor-wrong-element: This type of editor cannot be initialized inside <textarea> element.', null );
  218. }
  219. const editor = new this( sourceElementOrData, config );
  220. resolve(
  221. editor.initPlugins()
  222. .then( () => {
  223. editor.ui.init();
  224. } )
  225. .then( () => {
  226. if ( !isHTMLElement && config.initialData ) {
  227. // Documented in core/editor/editorconfig.jdoc.
  228. throw new CKEditorError(
  229. 'editor-create-initial-data: ' +
  230. 'The config.initialData option cannot be used together with initial data passed in Editor.create().',
  231. null
  232. );
  233. }
  234. const initialData = config.initialData || getInitialData( sourceElementOrData );
  235. return editor.data.init( initialData );
  236. } )
  237. .then( () => editor.fire( 'ready' ) )
  238. .then( () => editor )
  239. );
  240. } );
  241. }
  242. }
  243. mix( DecoupledEditor, DataApiMixin );
  244. function getInitialData( sourceElementOrData ) {
  245. return isElement( sourceElementOrData ) ? getDataFromElement( sourceElementOrData ) : sourceElementOrData;
  246. }