8
0

view.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/view/view
  7. */
  8. import Document from './document';
  9. import DowncastWriter from './downcastwriter';
  10. import Renderer from './renderer';
  11. import DomConverter from './domconverter';
  12. import Position from './position';
  13. import Range from './range';
  14. import Selection from './selection';
  15. import MutationObserver from './observer/mutationobserver';
  16. import KeyObserver from './observer/keyobserver';
  17. import FakeSelectionObserver from './observer/fakeselectionobserver';
  18. import SelectionObserver from './observer/selectionobserver';
  19. import FocusObserver from './observer/focusobserver';
  20. import CompositionObserver from './observer/compositionobserver';
  21. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  22. import log from '@ckeditor/ckeditor5-utils/src/log';
  23. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  24. import { scrollViewportToShowTarget } from '@ckeditor/ckeditor5-utils/src/dom/scroll';
  25. import { injectUiElementHandling } from './uielement';
  26. import { injectQuirksHandling } from './filler';
  27. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  28. /**
  29. * Editor's view controller class. Its main responsibility is DOM - View management for editing purposes, to provide
  30. * abstraction over the DOM structure and events and hide all browsers quirks.
  31. *
  32. * View controller renders view document to DOM whenever view structure changes. To determine when view can be rendered,
  33. * all changes need to be done using the {@link module:engine/view/view~View#change} method, using
  34. * {@link module:engine/view/downcastwriter~DowncastWriter}:
  35. *
  36. * view.change( writer => {
  37. * writer.insert( position, writer.createText( 'foo' ) );
  38. * } );
  39. *
  40. * View controller also register {@link module:engine/view/observer/observer~Observer observers} which observes changes
  41. * on DOM and fire events on the {@link module:engine/view/document~Document Document}.
  42. * Note that the following observers are added by the class constructor and are always available:
  43. *
  44. * * {@link module:engine/view/observer/mutationobserver~MutationObserver},
  45. * * {@link module:engine/view/observer/selectionobserver~SelectionObserver},
  46. * * {@link module:engine/view/observer/focusobserver~FocusObserver},
  47. * * {@link module:engine/view/observer/keyobserver~KeyObserver},
  48. * * {@link module:engine/view/observer/fakeselectionobserver~FakeSelectionObserver}.
  49. * * {@link module:engine/view/observer/compositionobserver~CompositionObserver}.
  50. *
  51. * This class also {@link module:engine/view/view~View#attachDomRoot binds the DOM and the view elements}.
  52. *
  53. * If you do not need full a DOM - view management, and only want to transform a tree of view elements to a tree of DOM
  54. * elements you do not need this controller. You can use the {@link module:engine/view/domconverter~DomConverter DomConverter} instead.
  55. *
  56. * @mixes module:utils/observablemixin~ObservableMixin
  57. */
  58. export default class View {
  59. constructor() {
  60. /**
  61. * Instance of the {@link module:engine/view/document~Document} associated with this view controller.
  62. *
  63. * @readonly
  64. * @type {module:engine/view/document~Document}
  65. */
  66. this.document = new Document();
  67. /**
  68. * Instance of the {@link module:engine/view/domconverter~DomConverter domConverter} use by
  69. * {@link module:engine/view/view~View#renderer renderer}
  70. * and {@link module:engine/view/observer/observer~Observer observers}.
  71. *
  72. * @readonly
  73. * @type {module:engine/view/domconverter~DomConverter}
  74. */
  75. this.domConverter = new DomConverter();
  76. /**
  77. * Instance of the {@link module:engine/view/renderer~Renderer renderer}.
  78. *
  79. * @protected
  80. * @type {module:engine/view/renderer~Renderer}
  81. */
  82. this._renderer = new Renderer( this.domConverter, this.document.selection );
  83. this._renderer.bind( 'isFocused' ).to( this.document );
  84. /**
  85. * Roots of the DOM tree. Map on the `HTMLElement`s with roots names as keys.
  86. *
  87. * @readonly
  88. * @type {Map.<String, HTMLElement>}
  89. */
  90. this.domRoots = new Map();
  91. /**
  92. * Map of registered {@link module:engine/view/observer/observer~Observer observers}.
  93. *
  94. * @private
  95. * @type {Map.<Function, module:engine/view/observer/observer~Observer>}
  96. */
  97. this._observers = new Map();
  98. /**
  99. * Is set to `true` when {@link #change view changes} are currently in progress.
  100. *
  101. * @private
  102. * @type {Boolean}
  103. */
  104. this._ongoingChange = false;
  105. /**
  106. * Used to prevent calling {@link #render} and {@link #change} during rendering view to the DOM.
  107. *
  108. * @private
  109. * @type {Boolean}
  110. */
  111. this._renderingInProgress = false;
  112. /**
  113. * Used to prevent calling {@link #render} and {@link #change} during rendering view to the DOM.
  114. *
  115. * @private
  116. * @type {Boolean}
  117. */
  118. this._postFixersInProgress = false;
  119. /**
  120. * Internal flag to temporary disable rendering. See the usage in the {@link #_disableRendering}.
  121. *
  122. * @private
  123. * @type {Boolean}
  124. */
  125. this._renderingDisabled = false;
  126. /**
  127. * Internal flag that disables rendering when there are no changes since the last rendering.
  128. * It stores information about changed selection and changed elements from attached document roots.
  129. *
  130. * @private
  131. * @type {Boolean}
  132. */
  133. this._hasChangedSinceTheLastRendering = false;
  134. /**
  135. * DowncastWriter instance used in {@link #change change method} callbacks.
  136. *
  137. * @private
  138. * @type {module:engine/view/downcastwriter~DowncastWriter}
  139. */
  140. this._writer = new DowncastWriter( this.document );
  141. // Add default observers.
  142. this.addObserver( MutationObserver );
  143. this.addObserver( SelectionObserver );
  144. this.addObserver( FocusObserver );
  145. this.addObserver( KeyObserver );
  146. this.addObserver( FakeSelectionObserver );
  147. this.addObserver( CompositionObserver );
  148. // Inject quirks handlers.
  149. injectQuirksHandling( this );
  150. injectUiElementHandling( this );
  151. // Use 'normal' priority so that rendering is performed as first when using that priority.
  152. this.on( 'render', () => {
  153. this._render();
  154. // Informs that layout has changed after render.
  155. this.document.fire( 'layoutChanged' );
  156. // Reset the `_hasChangedSinceTheLastRendering` flag after rendering.
  157. this._hasChangedSinceTheLastRendering = false;
  158. } );
  159. // Listen to the document selection changes directly.
  160. this.listenTo( this.document.selection, 'change', () => {
  161. this._hasChangedSinceTheLastRendering = true;
  162. } );
  163. }
  164. /**
  165. * Disables or enables rendering. If the flag is set to `true` then the rendering will be disabled.
  166. * If the flag is set to `false` and if there was some change in the meantime, then the rendering action will be performed.
  167. *
  168. * @protected
  169. * @param {Boolean} flag A flag indicates whether the rendering should be disabled.
  170. */
  171. _disableRendering( flag ) {
  172. this._renderingDisabled = flag;
  173. if ( flag == false ) {
  174. // Render when you stop blocking rendering.
  175. this.change( () => {} );
  176. }
  177. }
  178. /**
  179. * Attaches DOM root element to the view element and enable all observers on that element.
  180. * Also {@link module:engine/view/renderer~Renderer#markToSync mark element} to be synchronized with the view
  181. * what means that all child nodes will be removed and replaced with content of the view root.
  182. *
  183. * This method also will change view element name as the same as tag name of given dom root.
  184. * Name is always transformed to lower case.
  185. *
  186. * @param {Element} domRoot DOM root element.
  187. * @param {String} [name='main'] Name of the root.
  188. */
  189. attachDomRoot( domRoot, name = 'main' ) {
  190. const viewRoot = this.document.getRoot( name );
  191. // Set view root name the same as DOM root tag name.
  192. viewRoot._name = domRoot.tagName.toLowerCase();
  193. this.domRoots.set( name, domRoot );
  194. this.domConverter.bindElements( domRoot, viewRoot );
  195. this._renderer.markToSync( 'children', viewRoot );
  196. this._renderer.domDocuments.add( domRoot.ownerDocument );
  197. viewRoot.on( 'change:children', ( evt, node ) => this._renderer.markToSync( 'children', node ) );
  198. viewRoot.on( 'change:attributes', ( evt, node ) => this._renderer.markToSync( 'attributes', node ) );
  199. viewRoot.on( 'change:text', ( evt, node ) => this._renderer.markToSync( 'text', node ) );
  200. viewRoot.on( 'change', () => {
  201. this._hasChangedSinceTheLastRendering = true;
  202. } );
  203. for ( const observer of this._observers.values() ) {
  204. observer.observe( domRoot, name );
  205. }
  206. }
  207. /**
  208. * Gets DOM root element.
  209. *
  210. * @param {String} [name='main'] Name of the root.
  211. * @returns {Element} DOM root element instance.
  212. */
  213. getDomRoot( name = 'main' ) {
  214. return this.domRoots.get( name );
  215. }
  216. /**
  217. * Creates observer of the given type if not yet created, {@link module:engine/view/observer/observer~Observer#enable enables} it
  218. * and {@link module:engine/view/observer/observer~Observer#observe attaches} to all existing and future
  219. * {@link #domRoots DOM roots}.
  220. *
  221. * Note: Observers are recognized by their constructor (classes). A single observer will be instantiated and used only
  222. * when registered for the first time. This means that features and other components can register a single observer
  223. * multiple times without caring whether it has been already added or not.
  224. *
  225. * @param {Function} Observer The constructor of an observer to add.
  226. * Should create an instance inheriting from {@link module:engine/view/observer/observer~Observer}.
  227. * @returns {module:engine/view/observer/observer~Observer} Added observer instance.
  228. */
  229. addObserver( Observer ) {
  230. let observer = this._observers.get( Observer );
  231. if ( observer ) {
  232. return observer;
  233. }
  234. observer = new Observer( this );
  235. this._observers.set( Observer, observer );
  236. for ( const [ name, domElement ] of this.domRoots ) {
  237. observer.observe( domElement, name );
  238. }
  239. observer.enable();
  240. return observer;
  241. }
  242. /**
  243. * Returns observer of the given type or `undefined` if such observer has not been added yet.
  244. *
  245. * @param {Function} Observer The constructor of an observer to get.
  246. * @returns {module:engine/view/observer/observer~Observer|undefined} Observer instance or undefined.
  247. */
  248. getObserver( Observer ) {
  249. return this._observers.get( Observer );
  250. }
  251. /**
  252. * Disables all added observers.
  253. */
  254. disableObservers() {
  255. for ( const observer of this._observers.values() ) {
  256. observer.disable();
  257. }
  258. }
  259. /**
  260. * Enables all added observers.
  261. */
  262. enableObservers() {
  263. for ( const observer of this._observers.values() ) {
  264. observer.enable();
  265. }
  266. }
  267. /**
  268. * Scrolls the page viewport and {@link #domRoots} with their ancestors to reveal the
  269. * caret, if not already visible to the user.
  270. */
  271. scrollToTheSelection() {
  272. const range = this.document.selection.getFirstRange();
  273. if ( range ) {
  274. scrollViewportToShowTarget( {
  275. target: this.domConverter.viewRangeToDom( range ),
  276. viewportOffset: 20
  277. } );
  278. }
  279. }
  280. /**
  281. * It will focus DOM element representing {@link module:engine/view/editableelement~EditableElement EditableElement}
  282. * that is currently having selection inside.
  283. */
  284. focus() {
  285. if ( !this.document.isFocused ) {
  286. const editable = this.document.selection.editableElement;
  287. if ( editable ) {
  288. this.domConverter.focus( editable );
  289. this.forceRender();
  290. } else {
  291. /**
  292. * Before focusing view document, selection should be placed inside one of the view's editables.
  293. * Normally its selection will be converted from model document (which have default selection), but
  294. * when using view document on its own, we need to manually place selection before focusing it.
  295. *
  296. * @error view-focus-no-selection
  297. */
  298. log.warn( 'view-focus-no-selection: There is no selection in any editable to focus.' );
  299. }
  300. }
  301. }
  302. /**
  303. * The `change()` method is the primary way of changing the view. You should use it to modify any node in the view tree.
  304. * It makes sure that after all changes are made the view is rendered to the DOM (assuming that the view will be changed
  305. * inside the callback). It prevents situations when the DOM is updated when the view state is not yet correct.It allows
  306. * to nest calls one inside another and still performs a single rendering after all those changes are made.
  307. * It also returns the return value of its callback.
  308. *
  309. * const text = view.change( writer => {
  310. * const newText = writer.createText( 'foo' );
  311. * writer.insert( position1, newText );
  312. *
  313. * view.change( writer => {
  314. * writer.insert( position2, writer.createText( 'bar' ) );
  315. * } );
  316. *
  317. * writer.remove( range );
  318. *
  319. * return newText;
  320. * } );
  321. *
  322. * When the outermost change block is done and rendering to the DOM is over the
  323. * {@link module:engine/view/view~View#event:render `View#render`} event is fired.
  324. *
  325. * This method throws a `applying-view-changes-on-rendering` error when
  326. * the change block is used after rendering to the DOM has started.
  327. *
  328. * @param {Function} callback Callback function which may modify the view.
  329. * @returns {*} Value returned by the callback.
  330. */
  331. change( callback ) {
  332. if ( this._renderingInProgress || this._postFixersInProgress ) {
  333. /**
  334. * Thrown when there is an attempt to make changes to the view tree when it is in incorrect state. This may
  335. * cause some unexpected behaviour and inconsistency between the DOM and the view.
  336. * This may be caused by:
  337. *
  338. * * calling {@link #change} or {@link #render} during rendering process,
  339. * * calling {@link #change} or {@link #render} inside of
  340. * {@link module:engine/view/document~Document#registerPostFixer post-fixer function}.
  341. *
  342. * @error cannot-change-view-tree
  343. */
  344. throw new CKEditorError(
  345. 'cannot-change-view-tree: ' +
  346. 'Attempting to make changes to the view when it is in an incorrect state: rendering or post-fixers are in progress. ' +
  347. 'This may cause some unexpected behavior and inconsistency between the DOM and the view.'
  348. );
  349. }
  350. // Recursive call to view.change() method - execute listener immediately.
  351. if ( this._ongoingChange ) {
  352. return callback( this._writer );
  353. }
  354. // This lock will assure that all recursive calls to view.change() will end up in same block - one "render"
  355. // event for all nested calls.
  356. this._ongoingChange = true;
  357. const callbackResult = callback( this._writer );
  358. this._ongoingChange = false;
  359. // This lock is used by editing controller to render changes from outer most model.change() once. As plugins might call
  360. // view.change() inside model.change() block - this will ensures that postfixers and rendering are called once after all changes.
  361. // Also, we don't need to render anything if there're no changes since last rendering.
  362. if ( !this._renderingDisabled && this._hasChangedSinceTheLastRendering ) {
  363. this._postFixersInProgress = true;
  364. this.document._callPostFixers( this._writer );
  365. this._postFixersInProgress = false;
  366. this.fire( 'render' );
  367. }
  368. return callbackResult;
  369. }
  370. render() {
  371. console.log( 'deprecated usage.' );
  372. this.forceRender();
  373. }
  374. /**
  375. * Renders {@link module:engine/view/document~Document view document} to DOM. If any view changes are
  376. * currently in progress, rendering will start after all {@link #change change blocks} are processed.
  377. *
  378. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `applying-view-changes-on-rendering` when
  379. * trying to re-render when rendering to DOM has already started.
  380. */
  381. forceRender() {
  382. this._hasChangedSinceTheLastRendering = true;
  383. this.change( () => {} );
  384. }
  385. /**
  386. * Destroys this instance. Makes sure that all observers are destroyed and listeners removed.
  387. */
  388. destroy() {
  389. for ( const observer of this._observers.values() ) {
  390. observer.destroy();
  391. }
  392. this.document.destroy();
  393. this.stopListening();
  394. }
  395. /**
  396. * Creates position at the given location. The location can be specified as:
  397. *
  398. * * a {@link module:engine/view/position~Position position},
  399. * * parent element and offset (offset defaults to `0`),
  400. * * parent element and `'end'` (sets position at the end of that element),
  401. * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
  402. *
  403. * This method is a shortcut to other constructors such as:
  404. *
  405. * * {@link #createPositionBefore},
  406. * * {@link #createPositionAfter},
  407. *
  408. * @param {module:engine/view/item~Item|module:engine/model/position~Position} itemOrPosition
  409. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  410. * first parameter is a {@link module:engine/view/item~Item view item}.
  411. */
  412. createPositionAt( itemOrPosition, offset ) {
  413. return Position._createAt( itemOrPosition, offset );
  414. }
  415. /**
  416. * Creates a new position after given view item.
  417. *
  418. * @param {module:engine/view/item~Item} item View item after which the position should be located.
  419. * @returns {module:engine/view/position~Position}
  420. */
  421. createPositionAfter( item ) {
  422. return Position._createAfter( item );
  423. }
  424. /**
  425. * Creates a new position before given view item.
  426. *
  427. * @param {module:engine/view/item~Item} item View item before which the position should be located.
  428. * @returns {module:engine/view/position~Position}
  429. */
  430. createPositionBefore( item ) {
  431. return Position._createBefore( item );
  432. }
  433. /**
  434. * Creates a range spanning from `start` position to `end` position.
  435. *
  436. * **Note:** This factory method creates it's own {@link module:engine/view/position~Position} instances basing on passed values.
  437. *
  438. * @param {module:engine/view/position~Position} start Start position.
  439. * @param {module:engine/view/position~Position} [end] End position. If not set, range will be collapsed at `start` position.
  440. * @returns {module:engine/view/range~Range}
  441. */
  442. createRange( start, end ) {
  443. return new Range( start, end );
  444. }
  445. /**
  446. * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
  447. *
  448. * @param {module:engine/view/item~Item} item
  449. * @returns {module:engine/view/range~Range}
  450. */
  451. createRangeOn( item ) {
  452. return Range._createOn( item );
  453. }
  454. /**
  455. * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
  456. * that element and ends after the last child of that element.
  457. *
  458. * @param {module:engine/view/element~Element} element Element which is a parent for the range.
  459. * @returns {module:engine/view/range~Range}
  460. */
  461. createRangeIn( element ) {
  462. return Range._createIn( element );
  463. }
  464. /**
  465. Creates new {@link module:engine/view/selection~Selection} instance.
  466. *
  467. * // Creates empty selection without ranges.
  468. * const selection = view.createSelection();
  469. *
  470. * // Creates selection at the given range.
  471. * const range = view.createRange( start, end );
  472. * const selection = view.createSelection( range );
  473. *
  474. * // Creates selection at the given ranges
  475. * const ranges = [ view.createRange( start1, end2 ), view.createRange( star2, end2 ) ];
  476. * const selection = view.createSelection( ranges );
  477. *
  478. * // Creates selection from the other selection.
  479. * const otherSelection = view.createSelection();
  480. * const selection = view.createSelection( otherSelection );
  481. *
  482. * // Creates selection from the document selection.
  483. * const selection = view.createSelection( editor.editing.view.document.selection );
  484. *
  485. * // Creates selection at the given position.
  486. * const position = view.createPositionFromPath( root, path );
  487. * const selection = view.createSelection( position );
  488. *
  489. * // Creates collapsed selection at the position of given item and offset.
  490. * const paragraph = view.createContainerElement( 'paragraph' );
  491. * const selection = view.createSelection( paragraph, offset );
  492. *
  493. * // Creates a range inside an {@link module:engine/view/element~Element element} which starts before the
  494. * // first child of that element and ends after the last child of that element.
  495. * const selection = view.createSelection( paragraph, 'in' );
  496. *
  497. * // Creates a range on an {@link module:engine/view/item~Item item} which starts before the item and ends
  498. * // just after the item.
  499. * const selection = view.createSelection( paragraph, 'on' );
  500. *
  501. * `Selection`'s factory method allow passing additional options (`backward`, `fake` and `label`) as the last argument.
  502. *
  503. * // Creates backward selection.
  504. * const selection = view.createSelection( range, { backward: true } );
  505. *
  506. * Fake selection does not render as browser native selection over selected elements and is hidden to the user.
  507. * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
  508. * represented in other way, for example by applying proper CSS class.
  509. *
  510. * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM
  511. * (and be properly handled by screen readers).
  512. *
  513. * // Creates fake selection with label.
  514. * const selection = view.createSelection( range, { fake: true, label: 'foo' } );
  515. *
  516. * @param {module:engine/view/selection~Selectable} [selectable=null]
  517. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Offset or place when selectable is an `Item`.
  518. * @param {Object} [options]
  519. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  520. * @param {Boolean} [options.fake] Sets this selection instance to be marked as `fake`.
  521. * @param {String} [options.label] Label for the fake selection.
  522. * @returns {module:engine/view/selection~Selection}
  523. */
  524. createSelection( selectable, placeOrOffset, options ) {
  525. return new Selection( selectable, placeOrOffset, options );
  526. }
  527. /**
  528. * Renders all changes. In order to avoid triggering the observers (e.g. mutations) all observers are disabled
  529. * before rendering and re-enabled after that.
  530. *
  531. * @private
  532. */
  533. _render() {
  534. this._renderingInProgress = true;
  535. this.disableObservers();
  536. this._renderer.render();
  537. this.enableObservers();
  538. this._renderingInProgress = false;
  539. }
  540. /**
  541. * Fired after a topmost {@link module:engine/view/view~View#change change block} and all
  542. * {@link module:engine/view/document~Document#registerPostFixer post-fixers} are executed.
  543. *
  544. * Actual rendering is performed as a first listener on 'normal' priority.
  545. *
  546. * view.on( 'render', () => {
  547. * // Rendering to the DOM is complete.
  548. * } );
  549. *
  550. * This event is useful when you want to update interface elements after the rendering, e.g. position of the
  551. * balloon panel. If you wants to change view structure use
  552. * {@link module:engine/view/document~Document#registerPostFixer post-fixers}.
  553. *
  554. * @event module:engine/view/view~View#event:render
  555. */
  556. }
  557. mix( View, ObservableMixin );