editingcontroller.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/controller/editingcontroller
  7. */
  8. import RootEditableElement from '../view/rooteditableelement';
  9. import View from '../view/view';
  10. import Mapper from '../conversion/mapper';
  11. import DowncastDispatcher from '../conversion/downcastdispatcher';
  12. import { insertText, remove } from '../conversion/downcast-converters';
  13. import { convertSelectionChange } from '../conversion/upcast-selection-converters';
  14. import { clearAttributes, convertCollapsedSelection, convertRangeSelection } from '../conversion/downcast-selection-converters';
  15. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  16. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  17. import Range from '../model/range';
  18. import Position from '../model/position';
  19. /**
  20. * Controller for the editing pipeline. The editing pipeline controls {@link ~EditingController#model model} rendering,
  21. * including selection handling. It also creates the {@link ~EditingController#view view} which builds a
  22. * browser-independent virtualization over the DOM elements. The editing controller also attaches default converters.
  23. *
  24. * @mixes module:utils/observablemixin~ObservableMixin
  25. */
  26. export default class EditingController {
  27. /**
  28. * Creates an editing controller instance.
  29. *
  30. * @param {module:engine/model/model~Model} model Editing model.
  31. */
  32. constructor( model ) {
  33. /**
  34. * Editor model.
  35. *
  36. * @readonly
  37. * @member {module:engine/model/model~Model}
  38. */
  39. this.model = model;
  40. /**
  41. * Editing view controller.
  42. *
  43. * @readonly
  44. * @member {module:engine/view/view~View}
  45. */
  46. this.view = new View();
  47. /**
  48. * Mapper which describes the model-view binding.
  49. *
  50. * @readonly
  51. * @member {module:engine/conversion/mapper~Mapper}
  52. */
  53. this.mapper = new Mapper();
  54. /**
  55. * Downcast dispatcher that converts changes from the model to {@link #view the editing view}.
  56. *
  57. * @readonly
  58. * @member {module:engine/conversion/downcastdispatcher~DowncastDispatcher} #downcastDispatcher
  59. */
  60. this.downcastDispatcher = new DowncastDispatcher( {
  61. mapper: this.mapper
  62. } );
  63. const doc = this.model.document;
  64. const selection = doc.selection;
  65. const markers = this.model.markers;
  66. // Whenever model document is changed, convert those changes to the view (using model.Document#differ).
  67. // Do it on 'low' priority, so changes are converted after other listeners did their job.
  68. // Also convert model selection.
  69. this.listenTo( doc, 'change', () => {
  70. this.view.change( writer => {
  71. this.downcastDispatcher.convertChanges( doc.differ, writer );
  72. this.downcastDispatcher.convertSelection( selection, markers, writer );
  73. } );
  74. }, { priority: 'low' } );
  75. // Convert selection from the view to the model when it changes in the view.
  76. this.listenTo( this.view.document, 'selectionChange', convertSelectionChange( this.model, this.mapper ) );
  77. // Attach default model converters.
  78. this.downcastDispatcher.on( 'insert:$text', insertText(), { priority: 'lowest' } );
  79. this.downcastDispatcher.on( 'remove', remove(), { priority: 'low' } );
  80. // Attach default model selection converters.
  81. this.downcastDispatcher.on( 'selection', clearAttributes(), { priority: 'low' } );
  82. this.downcastDispatcher.on( 'selection', convertRangeSelection(), { priority: 'low' } );
  83. this.downcastDispatcher.on( 'selection', convertCollapsedSelection(), { priority: 'low' } );
  84. // Add selection post fixer.
  85. doc.registerPostFixer( writer => selectionPostFixer( writer, model ) );
  86. // Binds {@link module:engine/view/document~Document#roots view roots collection} to
  87. // {@link module:engine/model/document~Document#roots model roots collection} so creating
  88. // model root automatically creates corresponding view root.
  89. this.view.document.roots.bindTo( this.model.document.roots ).using( root => {
  90. // $graveyard is a special root that has no reflection in the view.
  91. if ( root.rootName == '$graveyard' ) {
  92. return null;
  93. }
  94. const viewRoot = new RootEditableElement( root.name );
  95. viewRoot.rootName = root.rootName;
  96. viewRoot._document = this.view.document;
  97. this.mapper.bindElements( root, viewRoot );
  98. return viewRoot;
  99. } );
  100. }
  101. /**
  102. * Removes all event listeners attached to the `EditingController`. Destroys all objects created
  103. * by `EditingController` that need to be destroyed.
  104. */
  105. destroy() {
  106. this.view.destroy();
  107. this.stopListening();
  108. }
  109. }
  110. mix( EditingController, ObservableMixin );
  111. /**
  112. * The selection post fixer which check if nodes with `isLimit` property in schema are properly selected.
  113. *
  114. * @param {module:engine/model/writer~Writer} writer
  115. * @param {module:engine/model/model~Model} model
  116. */
  117. function selectionPostFixer( writer, model ) {
  118. const selection = model.document.selection;
  119. const schema = model.schema;
  120. const ranges = [];
  121. let wasFixed = false;
  122. for ( const modelRange of selection.getRanges() ) {
  123. // Go through all ranges in selection and try fixing each of them.
  124. // Those ranges might overlap but will be corrected later.
  125. const correctedRange = tryFixRangeWithIsLimitBlocks( modelRange, schema );
  126. if ( correctedRange ) {
  127. ranges.push( correctedRange );
  128. wasFixed = true;
  129. } else {
  130. ranges.push( modelRange );
  131. }
  132. }
  133. // If any of ranges were corrected update the selection.
  134. if ( wasFixed ) {
  135. // The above algorithm might create ranges that intersects each other when selection contains more then one range.
  136. // This is case happens mostly on Firefox which creates multiple ranges for selected table.
  137. const safeRange = combineRangesOnLimitNodes( ranges );
  138. writer.setSelection( safeRange, { backward: selection.isBackward } );
  139. }
  140. }
  141. // Tries to correct a range if it contains blocks defined as `isLimit` in schema.
  142. //
  143. // @param {module:engine/model/range~Range} range
  144. // @param {module:engine/model/schema~Schema} schema
  145. // @returns {module:engine/model/range~Range|null} Returns fixed range or null if range is valid.
  146. function tryFixRangeWithIsLimitBlocks( range, schema ) {
  147. if ( range.isCollapsed ) {
  148. return tryFixCollapsedRange( range, schema );
  149. }
  150. return tryFixExpandedRange( range, schema );
  151. }
  152. // Tries to fix collapsed ranges - ie. when collapsed selection is in limit node that contains other limit nodes.
  153. //
  154. // @param {module:engine/model/range~Range} range Collapsed range to fix.
  155. // @param {module:engine/model/schema~Schema} schema
  156. // @returns {module:engine/model/range~Range|null} Returns fixed range or null if range is valid.
  157. function tryFixCollapsedRange( range, schema ) {
  158. const originalPosition = range.start;
  159. const nearestSelectionRange = schema.getNearestSelectionRange( originalPosition );
  160. // This might be null ie when editor data is empty.
  161. // In such cases there is no need to fix the selection range.
  162. if ( !nearestSelectionRange ) {
  163. return null;
  164. }
  165. const fixedPosition = nearestSelectionRange.start;
  166. // Fixed position is the same as original - no need to return corrected range.
  167. if ( originalPosition.isEqual( fixedPosition ) ) {
  168. return null;
  169. }
  170. // Check single node selection (happens in tables).
  171. if ( fixedPosition.nodeAfter && schema.isLimit( fixedPosition.nodeAfter ) ) {
  172. return new Range( fixedPosition, Position.createAfter( fixedPosition.nodeAfter ) );
  173. }
  174. return new Range( fixedPosition );
  175. }
  176. // Tries to fix a expanded range that overlaps limit nodes.
  177. //
  178. // @param {module:engine/model/range~Range} range Expanded range to fix.
  179. // @param {module:engine/model/schema~Schema} schema
  180. // @returns {module:engine/model/range~Range|null} Returns fixed range or null if range is valid.
  181. function tryFixExpandedRange( range, schema ) {
  182. // No need to check flat ranges as they will not cross node boundary.
  183. if ( range.isFlat ) {
  184. return null;
  185. }
  186. const start = range.start;
  187. const end = range.end;
  188. const updatedStart = expandSelectionOnIsLimitNode( start, schema, 'start' );
  189. const updatedEnd = expandSelectionOnIsLimitNode( end, schema, 'end' );
  190. if ( !start.isEqual( updatedStart ) || !end.isEqual( updatedEnd ) ) {
  191. return new Range( updatedStart, updatedEnd );
  192. }
  193. return null;
  194. }
  195. // Expands selection so it contains whole limit node.
  196. //
  197. // @param {module:engine/model/position~Position} position
  198. // @param {module:engine/model/schema~Schema} schema
  199. // @param {String} expandToDirection Direction of expansion - either 'start' or 'end' of the range.
  200. // @returns {module:engine/model/position~Position}
  201. function expandSelectionOnIsLimitNode( position, schema, expandToDirection ) {
  202. let node = position.parent;
  203. let parent = node;
  204. // Find outer most isLimit block as such blocks might be nested (ie. in tables).
  205. while ( schema.isLimit( parent ) && parent.parent ) {
  206. node = parent;
  207. parent = parent.parent;
  208. }
  209. if ( node === parent ) {
  210. // If there is not is limit block the return original position.
  211. return position;
  212. }
  213. // Depending on direction of expanding selection return position before or after found node.
  214. return expandToDirection === 'start' ? Position.createBefore( node ) : Position.createAfter( node );
  215. }
  216. // Returns minimal set of continuous ranges.
  217. //
  218. // @param {Array.<module:engine/model/range~Range>} ranges
  219. // @returns {Array.<module:engine/model/range~Range>}
  220. function combineRangesOnLimitNodes( ranges ) {
  221. const combinedRanges = [];
  222. let previousRange;
  223. for ( let i = 0; i < ranges.length; i++ ) {
  224. const range = ranges[ i ];
  225. if ( !previousRange ) {
  226. previousRange = range;
  227. combinedRanges.push( previousRange );
  228. continue;
  229. }
  230. // Do not push same ranges (ie might be created in a table)
  231. if ( range.isEqual( previousRange ) ) {
  232. continue;
  233. }
  234. if ( range.isIntersecting( previousRange ) ) {
  235. const newStart = previousRange.start.isBefore( range.start ) ? previousRange.start : range.start;
  236. const newEnd = range.end.isAfter( previousRange.end ) ? range.end : previousRange.end;
  237. const newRange = new Range( newStart, newEnd );
  238. combinedRanges.splice( combinedRanges.indexOf( previousRange ), 1, newRange );
  239. previousRange = newRange;
  240. continue;
  241. }
  242. previousRange = range;
  243. combinedRanges.push( range );
  244. }
  245. return combinedRanges;
  246. }