treewalker.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import CharacterProxy from './characterproxy.js';
  7. import TextProxy from './textproxy.js';
  8. import Element from './element.js';
  9. import Position from './position.js';
  10. import CKEditorError from '../../utils/ckeditorerror.js';
  11. /**
  12. * Position iterator class. It allows to iterate forward and backward over the document.
  13. *
  14. * @memberOf engine.model
  15. */
  16. export default class TreeWalker {
  17. /**
  18. * Creates a range iterator. All parameters are optional, but you have to specify either `boundaries` or `startPosition`.
  19. *
  20. * @constructor
  21. * @param {Object} [options={}] Object with configuration.
  22. * @param {'FORWARD'|'BACKWARD'} [options.direction='FORWARD'] Walking direction.
  23. * @param {engine.model.Range} [options.boundaries=null] Range to define boundaries of the iterator.
  24. * @param {engine.model.Position} [options.startPosition] Starting position.
  25. * @param {Boolean} [options.singleCharacters=false] Flag indicating whether all consecutive characters with the same attributes
  26. * should be returned one by one as multiple {@link engine.model.CharacterProxy} (`true`) objects or as one
  27. * {@link engine.model.TextProxy} (`false`).
  28. * @param {Boolean} [options.shallow=false] Flag indicating whether iterator should enter elements or not. If the
  29. * iterator is shallow child nodes of any iterated node will not be returned along with `elementEnd` tag.
  30. * @param {Boolean} [options.ignoreElementEnd=false] Flag indicating whether iterator should ignore `elementEnd`
  31. * tags. If the option is true walker will not return a parent node of start position. If this option is `true`
  32. * each {@link engine.model.Element} will be returned once, while if the option is `false` they might be returned
  33. * twice: for `'elementStart'` and `'elementEnd'`.
  34. */
  35. constructor( options = {} ) {
  36. if ( !options.boundaries && !options.startPosition ) {
  37. /**
  38. * Neither boundaries nor starting position have been defined.
  39. *
  40. * @error tree-walker-no-start-position
  41. */
  42. throw new CKEditorError( 'tree-walker-no-start-position: Neither boundaries nor starting position have been defined.' );
  43. }
  44. const direction = options.direction || 'FORWARD';
  45. if ( direction != 'FORWARD' && direction != 'BACKWARD' ) {
  46. throw new CKEditorError(
  47. 'tree-walker-unknown-direction: Only `BACKWARD` and `FORWARD` direction allowed.',
  48. { direction }
  49. );
  50. }
  51. /**
  52. * Walking direction. Defaults `FORWARD`.
  53. *
  54. * @readonly
  55. * @member {'BACKWARD'|'FORWARD'} engine.model.TreeWalker#direction
  56. */
  57. this.direction = direction;
  58. /**
  59. * Iterator boundaries.
  60. *
  61. * When the iterator is walking `FORWARD` on the end of boundary or is walking `BACKWARD`
  62. * on the start of boundary, then `{ done: true }` is returned.
  63. *
  64. * If boundaries are not defined they are set before first and after last child of the root node.
  65. *
  66. * @readonly
  67. * @member {engine.model.Range} engine.model.TreeWalker#boundaries
  68. */
  69. this.boundaries = options.boundaries || null;
  70. /**
  71. * Iterator position. This is always static position, even if the initial position was a
  72. * {@link engine.model.LivePosition live position}. If start position is not defined then position depends
  73. * on {@link #direction}. If direction is `FORWARD` position starts form the beginning, when direction
  74. * is `BACKWARD` position starts from the end.
  75. *
  76. * @readonly
  77. * @member {engine.model.Position} engine.model.TreeWalker#position
  78. */
  79. if ( options.startPosition ) {
  80. this.position = Position.createFromPosition( options.startPosition );
  81. } else {
  82. this.position = Position.createFromPosition( this.boundaries[ this.direction == 'BACKWARD' ? 'end' : 'start' ] );
  83. }
  84. /**
  85. * Flag indicating whether all consecutive characters with the same attributes should be
  86. * returned as one {@link engine.model.CharacterProxy} (`true`) or one by one (`false`).
  87. *
  88. * @readonly
  89. * @member {Boolean} engine.model.TreeWalker#singleCharacters
  90. */
  91. this.singleCharacters = !!options.singleCharacters;
  92. /**
  93. * Flag indicating whether iterator should enter elements or not. If the iterator is shallow child nodes of any
  94. * iterated node will not be returned along with `elementEnd` tag.
  95. *
  96. * @readonly
  97. * @member {Boolean} engine.model.TreeWalker#shallow
  98. */
  99. this.shallow = !!options.shallow;
  100. /**
  101. * Flag indicating whether iterator should ignore `elementEnd` tags. If the option is true walker will not
  102. * return a parent node of the start position. If this option is `true` each {@link engine.model.Element} will
  103. * be returned once, while if the option is `false` they might be returned twice:
  104. * for `'elementStart'` and `'elementEnd'`.
  105. *
  106. * @readonly
  107. * @member {Boolean} engine.model.TreeWalker#ignoreElementEnd
  108. */
  109. this.ignoreElementEnd = !!options.ignoreElementEnd;
  110. /**
  111. * Start boundary cached for optimization purposes.
  112. *
  113. * @private
  114. * @member {engine.model.Element} engine.model.TreeWalker#_boundaryStartParent
  115. */
  116. this._boundaryStartParent = this.boundaries ? this.boundaries.start.parent : null;
  117. /**
  118. * End boundary cached for optimization purposes.
  119. *
  120. * @private
  121. * @member {engine.model.Element} engine.model.TreeWalker#_boundaryEndParent
  122. */
  123. this._boundaryEndParent = this.boundaries ? this.boundaries.end.parent : null;
  124. /**
  125. * Parent of the most recently visited node. Cached for optimization purposes.
  126. *
  127. * @private
  128. * @member {engine.model.Element|engine.model.DocumentFragment} engine.model.TreeWalker#_visitedParent
  129. */
  130. this._visitedParent = this.position.parent;
  131. }
  132. /**
  133. * Iterator interface.
  134. */
  135. [ Symbol.iterator ]() {
  136. return this;
  137. }
  138. /**
  139. * Iterator interface method.
  140. * Detects walking direction and makes step forward or backward.
  141. *
  142. * @returns {Object} Object implementing iterator interface, returning information about taken step.
  143. */
  144. next() {
  145. if ( this.direction == 'FORWARD' ) {
  146. return this._next();
  147. } else {
  148. return this._previous();
  149. }
  150. }
  151. /**
  152. * Makes a step forward in model. Moves the {@link #position} to the next position and returns the encountered value.
  153. *
  154. * @private
  155. * @returns {Object}
  156. * @returns {Boolean} return.done True if iterator is done.
  157. * @returns {engine.model.TreeWalkerValue} return.value Information about taken step.
  158. */
  159. _next() {
  160. const previousPosition = this.position;
  161. const position = Position.createFromPosition( this.position );
  162. const parent = this._visitedParent;
  163. // We are at the end of the root.
  164. if ( parent.parent === null && position.offset === parent.getChildCount() ) {
  165. return { done: true };
  166. }
  167. // We reached the walker boundary.
  168. if ( parent === this._boundaryEndParent && position.offset == this.boundaries.end.offset ) {
  169. return { done: true };
  170. }
  171. const node = parent.getChild( position.offset );
  172. if ( node instanceof Element ) {
  173. if ( !this.shallow ) {
  174. // Manual operations on path internals for optimization purposes. Here and in the rest of the method.
  175. position.path.push( 0 );
  176. this._visitedParent = node;
  177. } else {
  178. position.offset++;
  179. }
  180. this.position = position;
  181. return formatReturnValue( 'elementStart', node, previousPosition, position, 1 );
  182. } else if ( node instanceof CharacterProxy ) {
  183. if ( this.singleCharacters ) {
  184. position.offset++;
  185. this.position = position;
  186. return formatReturnValue( 'CHARACTER', node, previousPosition, position, 1 );
  187. } else {
  188. let charactersCount = node._nodeListText.text.length - node._index;
  189. let offset = position.offset + charactersCount;
  190. if ( this._boundaryEndParent == parent && this.boundaries.end.offset < offset ) {
  191. offset = this.boundaries.end.offset;
  192. charactersCount = offset - position.offset;
  193. }
  194. let textProxy = new TextProxy( node, charactersCount );
  195. position.offset = offset;
  196. this.position = position;
  197. return formatReturnValue( 'text', textProxy, previousPosition, position, charactersCount );
  198. }
  199. } else {
  200. // `node` is not set, we reached the end of current `parent`.
  201. position.path.pop();
  202. position.offset++;
  203. this.position = position;
  204. this._visitedParent = parent.parent;
  205. if ( this.ignoreElementEnd ) {
  206. return this._next();
  207. } else {
  208. return formatReturnValue( 'elementEnd', parent, previousPosition, position );
  209. }
  210. }
  211. }
  212. /**
  213. * Makes a step backward in model. Moves the {@link #position} to the previous position and returns the encountered value.
  214. *
  215. * @private
  216. * @returns {Object}
  217. * @returns {Boolean} return.done True if iterator is done.
  218. * @returns {engine.model.TreeWalkerValue} return.value Information about taken step.
  219. */
  220. _previous() {
  221. const previousPosition = this.position;
  222. const position = Position.createFromPosition( this.position );
  223. const parent = this._visitedParent;
  224. // We are at the beginning of the root.
  225. if ( parent.parent === null && position.offset === 0 ) {
  226. return { done: true };
  227. }
  228. // We reached the walker boundary.
  229. if ( parent == this._boundaryStartParent && position.offset == this.boundaries.start.offset ) {
  230. return { done: true };
  231. }
  232. // Get node just before current position
  233. const node = parent.getChild( position.offset - 1 );
  234. if ( node instanceof Element ) {
  235. position.offset--;
  236. if ( !this.shallow ) {
  237. position.path.push( node.getChildCount() );
  238. this.position = position;
  239. this._visitedParent = node;
  240. if ( this.ignoreElementEnd ) {
  241. return this._previous();
  242. } else {
  243. return formatReturnValue( 'elementEnd', node, previousPosition, position );
  244. }
  245. } else {
  246. this.position = position;
  247. return formatReturnValue( 'elementStart', node, previousPosition, position, 1 );
  248. }
  249. } else if ( node instanceof CharacterProxy ) {
  250. if ( this.singleCharacters ) {
  251. position.offset--;
  252. this.position = position;
  253. return formatReturnValue( 'CHARACTER', node, previousPosition, position, 1 );
  254. } else {
  255. let charactersCount = node._index + 1;
  256. let offset = position.offset - charactersCount;
  257. if ( this._boundaryStartParent == parent && this.boundaries.start.offset > offset ) {
  258. offset = this.boundaries.start.offset;
  259. charactersCount = position.offset - offset;
  260. }
  261. let textFragment = new TextProxy( parent.getChild( offset ), charactersCount );
  262. position.offset = offset;
  263. this.position = position;
  264. return formatReturnValue( 'text', textFragment, previousPosition, position, charactersCount );
  265. }
  266. } else {
  267. // `node` is not set, we reached the beginning of current `parent`.
  268. position.path.pop();
  269. this.position = position;
  270. this._visitedParent = parent.parent;
  271. return formatReturnValue( 'elementStart', parent, previousPosition, position, 1 );
  272. }
  273. }
  274. }
  275. function formatReturnValue( type, item, previousPosition, nextPosition, length ) {
  276. return {
  277. done: false,
  278. value: {
  279. type: type,
  280. item: item,
  281. previousPosition: previousPosition,
  282. nextPosition: nextPosition,
  283. length: length
  284. }
  285. };
  286. }
  287. /**
  288. * Type of the step made by {@link engine.model.TreeWalker}.
  289. * Possible values: `'elementStart'` if walker is at the beginning of a node, `'elementEnd'` if walker is at the end of node,
  290. * `'CHARACTER'` if walker traversed over a character, or `'text'` if walker traversed over multiple characters (available in
  291. * character merging mode, see {@link engine.model.TreeWalker#constructor}).
  292. *
  293. * @typedef {String} engine.model.TreeWalkerValueType
  294. */
  295. /**
  296. * Object returned by {@link engine.model.TreeWalker} when traversing tree model.
  297. *
  298. * @typedef {Object} engine.model.TreeWalkerValue
  299. * @property {engine.model.TreeWalkerValueType} type
  300. * @property {engine.model.Item} item Item between old and new positions of {@link engine.model.TreeWalker}.
  301. * @property {engine.model.Position} previousPosition Previous position of the iterator.
  302. * * Forward iteration: For `'elementEnd'` it is the last position inside the element. For all other types it is the
  303. * position before the item. Note that it is more efficient to use this position then calculate the position before
  304. * the node using {@link engine.model.Position.createBefore}. It is also more efficient to get the
  305. * position after node by shifting `previousPosition` by `length`, using {@link engine.model.Position#getShiftedBy},
  306. * then calculate the position using {@link engine.model.Position.createAfter}.
  307. * * Backward iteration: For `'elementStart'` it is the first position inside the element. For all other types it is
  308. * the position after item.
  309. * @property {engine.model.Position} nextPosition Next position of the iterator.
  310. * * Forward iteration: For `'elementStart'` it is the first position inside the element. For all other types it is
  311. * the position after the item.
  312. * * Backward iteration: For `'elementEnd'` it is last position inside element. For all other types it is the position
  313. * before the item.
  314. * @property {Number} [length] Length of the item. For `'elementStart'` and `'CHARACTER'` it is 1. For `'text'` it is
  315. * the length of the text. For `'elementEnd'` it is undefined.
  316. */
  317. /**
  318. * Tree walking directions.
  319. *
  320. * @typedef {'FORWARD'|'BACKWARD'} engine.view.TreeWalkerDirection
  321. */