treewalker.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/treewalker
  7. */
  8. import Text from './text';
  9. import TextProxy from './textproxy';
  10. import Element from './element';
  11. import Position from './position';
  12. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  13. /**
  14. * Position iterator class. It allows to iterate forward and backward over the document.
  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 {module:engine/model/range~Range} [options.boundaries=null] Range to define boundaries of the iterator.
  24. * @param {module:engine/model/position~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 module:engine/model/textproxy~TextProxy} (`true`) objects or as one
  27. * {@link module:engine/model/textproxy~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 module:engine/model/element~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 of a `TreeWalker` have been defined.
  39. *
  40. * @error model-tree-walker-no-start-position
  41. */
  42. throw new CKEditorError( 'model-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. 'model-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'} module:engine/model/treewalker~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 {module:engine/model/range~Range} module:engine/model/treewalker~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 module:engine/model/liveposition~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 {module:engine/model/position~Position} module:engine/model/treewalker~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 module:engine/model/textproxy~TextProxy} (`true`) or one by one (`false`).
  87. *
  88. * @readonly
  89. * @member {Boolean} module:engine/model/treewalker~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} module:engine/model/treewalker~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 module:engine/model/element~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} module:engine/model/treewalker~TreeWalker#ignoreElementEnd
  108. */
  109. this.ignoreElementEnd = !!options.ignoreElementEnd;
  110. /**
  111. * Start boundary cached for optimization purposes.
  112. *
  113. * @private
  114. * @member {module:engine/model/element~Element} module:engine/model/treewalker~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 {module:engine/model/element~Element} module:engine/model/treewalker~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 {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
  129. * module:engine/model/treewalker~TreeWalker#_visitedParent
  130. */
  131. this._visitedParent = this.position.parent;
  132. }
  133. /**
  134. * Iterable interface.
  135. *
  136. * @returns {Iterable.<module:engine/model/treewalker~TreeWalkerValue>}
  137. */
  138. [ Symbol.iterator ]() {
  139. return this;
  140. }
  141. /**
  142. * Moves {@link #position} in the {@link #direction} skipping values as long as the callback function returns `true`.
  143. *
  144. * For example:
  145. *
  146. * walker.skip( value => value.type == 'text' ); // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
  147. * walker.skip( () => true ); // Move the position to the end: <paragraph>[]foo</paragraph> -> <paragraph>foo</paragraph>[]
  148. * walker.skip( () => false ); // Do not move the position.
  149. *
  150. * @param {Function} skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
  151. * return `true` if the value should be skipped or `false` if not.
  152. */
  153. skip( skip ) {
  154. let done, value, prevPosition, prevVisitedParent;
  155. do {
  156. prevPosition = this.position;
  157. prevVisitedParent = this._visitedParent;
  158. ( { done, value } = this.next() );
  159. } while ( !done && skip( value ) );
  160. if ( !done ) {
  161. this.position = prevPosition;
  162. this._visitedParent = prevVisitedParent;
  163. }
  164. }
  165. /**
  166. * Gets the next tree walker's value.
  167. *
  168. * @returns {module:engine/model/treewalker~TreeWalkerValue} Next tree walker's value.
  169. */
  170. next() {
  171. if ( this.direction == 'forward' ) {
  172. return this._next();
  173. } else {
  174. return this._previous();
  175. }
  176. }
  177. /**
  178. * Makes a step forward in model. Moves the {@link #position} to the next position and returns the encountered value.
  179. *
  180. * @private
  181. * @returns {Object}
  182. * @returns {Boolean} return.done True if iterator is done.
  183. * @returns {module:engine/model/treewalker~TreeWalkerValue} return.value Information about taken step.
  184. */
  185. _next() {
  186. const previousPosition = this.position;
  187. const position = Position.createFromPosition( this.position );
  188. const parent = this._visitedParent;
  189. // We are at the end of the root.
  190. if ( parent.parent === null && position.offset === parent.maxOffset ) {
  191. return { done: true };
  192. }
  193. // We reached the walker boundary.
  194. if ( parent === this._boundaryEndParent && position.offset == this.boundaries.end.offset ) {
  195. return { done: true };
  196. }
  197. const node = position.textNode ? position.textNode : position.nodeAfter;
  198. if ( node instanceof Element ) {
  199. if ( !this.shallow ) {
  200. // Manual operations on path internals for optimization purposes. Here and in the rest of the method.
  201. position.path.push( 0 );
  202. this._visitedParent = node;
  203. } else {
  204. position.offset++;
  205. }
  206. this.position = position;
  207. return formatReturnValue( 'elementStart', node, previousPosition, position, 1 );
  208. } else if ( node instanceof Text ) {
  209. let charactersCount;
  210. if ( this.singleCharacters ) {
  211. charactersCount = 1;
  212. } else {
  213. let offset = node.endOffset;
  214. if ( this._boundaryEndParent == parent && this.boundaries.end.offset < offset ) {
  215. offset = this.boundaries.end.offset;
  216. }
  217. charactersCount = offset - position.offset;
  218. }
  219. const offsetInTextNode = position.offset - node.startOffset;
  220. const item = new TextProxy( node, offsetInTextNode, charactersCount );
  221. position.offset += charactersCount;
  222. this.position = position;
  223. return formatReturnValue( 'text', item, previousPosition, position, charactersCount );
  224. } else {
  225. // `node` is not set, we reached the end of current `parent`.
  226. position.path.pop();
  227. position.offset++;
  228. this.position = position;
  229. this._visitedParent = parent.parent;
  230. if ( this.ignoreElementEnd ) {
  231. return this._next();
  232. } else {
  233. return formatReturnValue( 'elementEnd', parent, previousPosition, position );
  234. }
  235. }
  236. }
  237. /**
  238. * Makes a step backward in model. Moves the {@link #position} to the previous position and returns the encountered value.
  239. *
  240. * @private
  241. * @returns {Object}
  242. * @returns {Boolean} return.done True if iterator is done.
  243. * @returns {module:engine/model/treewalker~TreeWalkerValue} return.value Information about taken step.
  244. */
  245. _previous() {
  246. const previousPosition = this.position;
  247. const position = Position.createFromPosition( this.position );
  248. const parent = this._visitedParent;
  249. // We are at the beginning of the root.
  250. if ( parent.parent === null && position.offset === 0 ) {
  251. return { done: true };
  252. }
  253. // We reached the walker boundary.
  254. if ( parent == this._boundaryStartParent && position.offset == this.boundaries.start.offset ) {
  255. return { done: true };
  256. }
  257. // Get node just before current position
  258. const node = position.textNode ? position.textNode : position.nodeBefore;
  259. if ( node instanceof Element ) {
  260. position.offset--;
  261. if ( !this.shallow ) {
  262. position.path.push( node.maxOffset );
  263. this.position = position;
  264. this._visitedParent = node;
  265. if ( this.ignoreElementEnd ) {
  266. return this._previous();
  267. } else {
  268. return formatReturnValue( 'elementEnd', node, previousPosition, position );
  269. }
  270. } else {
  271. this.position = position;
  272. return formatReturnValue( 'elementStart', node, previousPosition, position, 1 );
  273. }
  274. } else if ( node instanceof Text ) {
  275. let charactersCount;
  276. if ( this.singleCharacters ) {
  277. charactersCount = 1;
  278. } else {
  279. let offset = node.startOffset;
  280. if ( this._boundaryStartParent == parent && this.boundaries.start.offset > offset ) {
  281. offset = this.boundaries.start.offset;
  282. }
  283. charactersCount = position.offset - offset;
  284. }
  285. const offsetInTextNode = position.offset - node.startOffset;
  286. const item = new TextProxy( node, offsetInTextNode - charactersCount, charactersCount );
  287. position.offset -= charactersCount;
  288. this.position = position;
  289. return formatReturnValue( 'text', item, previousPosition, position, charactersCount );
  290. } else {
  291. // `node` is not set, we reached the beginning of current `parent`.
  292. position.path.pop();
  293. this.position = position;
  294. this._visitedParent = parent.parent;
  295. return formatReturnValue( 'elementStart', parent, previousPosition, position, 1 );
  296. }
  297. }
  298. }
  299. function formatReturnValue( type, item, previousPosition, nextPosition, length ) {
  300. return {
  301. done: false,
  302. value: {
  303. type,
  304. item,
  305. previousPosition,
  306. nextPosition,
  307. length
  308. }
  309. };
  310. }
  311. /**
  312. * Type of the step made by {@link module:engine/model/treewalker~TreeWalker}.
  313. * Possible values: `'elementStart'` if walker is at the beginning of a node, `'elementEnd'` if walker is at the end of node,
  314. * `'character'` if walker traversed over a character, or `'text'` if walker traversed over multiple characters (available in
  315. * character merging mode, see {@link module:engine/model/treewalker~TreeWalker#constructor}).
  316. *
  317. * @typedef {'elementStart'|'elementEnd'|'character'|'text'} module:engine/model/treewalker~TreeWalkerValueType
  318. */
  319. /**
  320. * Object returned by {@link module:engine/model/treewalker~TreeWalker} when traversing tree model.
  321. *
  322. * @typedef {Object} module:engine/model/treewalker~TreeWalkerValue
  323. * @property {module:engine/model/treewalker~TreeWalkerValueType} type
  324. * @property {module:engine/model/item~Item} item Item between old and new positions of {@link module:engine/model/treewalker~TreeWalker}.
  325. * @property {module:engine/model/position~Position} previousPosition Previous position of the iterator.
  326. * * Forward iteration: For `'elementEnd'` it is the last position inside the element. For all other types it is the
  327. * position before the item. Note that it is more efficient to use this position then calculate the position before
  328. * the node using {@link module:engine/model/position~Position.createBefore}. It is also more efficient to get the
  329. * position after node by shifting `previousPosition` by `length`, using {@link module:engine/model/position~Position#getShiftedBy},
  330. * then calculate the position using {@link module:engine/model/position~Position.createAfter}.
  331. * * Backward iteration: For `'elementStart'` it is the first position inside the element. For all other types it is
  332. * the position after item.
  333. * @property {module:engine/model/position~Position} nextPosition Next position of the iterator.
  334. * * Forward iteration: For `'elementStart'` it is the first position inside the element. For all other types it is
  335. * the position after the item.
  336. * * Backward iteration: For `'elementEnd'` it is last position inside element. For all other types it is the position
  337. * before the item.
  338. * @property {Number} [length] Length of the item. For `'elementStart'` and `'character'` it is 1. For `'text'` it is
  339. * the length of the text. For `'elementEnd'` it is undefined.
  340. */
  341. /**
  342. * Tree walking directions.
  343. *
  344. * @typedef {'forward'|'backward'} module:engine/view/treewalker~TreeWalkerDirection
  345. */