8
0

treewalker.js 13 KB

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