8
0

view.js 26 KB

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