treewalker.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/view/treewalker
  7. */
  8. import Element from './element';
  9. import Text from './text';
  10. import TextProxy from './textproxy';
  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 {module:engine/view/range~Range} [options.boundaries=null] Range to define boundaries of the iterator.
  23. * @param {module:engine/view/position~Position} [options.startPosition] Starting position.
  24. * @param {'forward'|'backward'} [options.direction='forward'] Walking direction.
  25. * @param {Boolean} [options.singleCharacters=false] Flag indicating whether all characters from
  26. * {@link module:engine/view/text~Text} should be returned as one {@link module:engine/view/text~Text} (`false`) ore one by one as
  27. * {@link module:engine/view/textproxy~TextProxy} (`true`).
  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/view/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 have been defined.
  39. *
  40. * @error view-tree-walker-no-start-position
  41. */
  42. throw new CKEditorError( 'view-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. 'view-tree-walker-unknown-direction: Only `backward` and `forward` direction allowed.',
  47. { direction: options.direction }
  48. );
  49. }
  50. /**
  51. * Iterator boundaries.
  52. *
  53. * When the iterator is walking `'forward'` on the end of boundary or is walking `'backward'`
  54. * on the start of 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 {module:engine/view/range~Range} module:engine/view/treewalker~TreeWalker#boundaries
  60. */
  61. this.boundaries = options.boundaries || null;
  62. /**
  63. * Iterator position. If start position is not defined then position depends on {@link #direction}. If direction is
  64. * `'forward'` position starts form the beginning, when direction is `'backward'` position starts from the end.
  65. *
  66. * @readonly
  67. * @member {module:engine/view/position~Position} module:engine/view/treewalker~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'} module:engine/view/treewalker~TreeWalker#direction
  79. */
  80. this.direction = options.direction || 'forward';
  81. /**
  82. * Flag indicating whether all characters from {@link module:engine/view/text~Text} should be returned as one
  83. * {@link module:engine/view/text~Text} or one by one as {@link module:engine/view/textproxy~TextProxy}.
  84. *
  85. * @readonly
  86. * @member {Boolean} module:engine/view/treewalker~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 `elementEnd` tag.
  92. *
  93. * @readonly
  94. * @member {Boolean} module:engine/view/treewalker~TreeWalker#shallow
  95. */
  96. this.shallow = !!options.shallow;
  97. /**
  98. * Flag indicating whether iterator should ignore `elementEnd` tags. If set to `true`, walker will not
  99. * return a parent node of the start position. Each {@link module:engine/view/element~Element} will be returned once.
  100. * When set to `false` each element might be returned twice: for `'elementStart'` and `'elementEnd'`.
  101. *
  102. * @readonly
  103. * @member {Boolean} module:engine/view/treewalker~TreeWalker#ignoreElementEnd
  104. */
  105. this.ignoreElementEnd = !!options.ignoreElementEnd;
  106. /**
  107. * Start boundary parent.
  108. *
  109. * @private
  110. * @member {module:engine/view/node~Node} module:engine/view/treewalker~TreeWalker#_boundaryStartParent
  111. */
  112. this._boundaryStartParent = this.boundaries ? this.boundaries.start.parent : null;
  113. /**
  114. * End boundary parent.
  115. *
  116. * @private
  117. * @member {module:engine/view/node~Node} module:engine/view/treewalker~TreeWalker#_boundaryEndParent
  118. */
  119. this._boundaryEndParent = this.boundaries ? this.boundaries.end.parent : null;
  120. }
  121. /**
  122. * Iterable interface.
  123. *
  124. * @returns {Iterable.<module:engine/view/treewalker~TreeWalkerValue>}
  125. */
  126. [ Symbol.iterator ]() {
  127. return this;
  128. }
  129. /**
  130. * Moves {@link #position} in the {@link #direction} skipping values as long as the callback function returns `true`.
  131. *
  132. * For example:
  133. *
  134. * walker.skip( value => value.type == 'text' ); // <p>{}foo</p> -> <p>foo[]</p>
  135. * walker.skip( value => true ); // Move the position to the end: <p>{}foo</p> -> <p>foo</p>[]
  136. * walker.skip( value => false ); // Do not move the position.
  137. *
  138. * @param {Function} skip Callback function. Gets {@link module:engine/view/treewalker~TreeWalkerValue} and should
  139. * return `true` if the value should be skipped or `false` if not.
  140. */
  141. skip( skip ) {
  142. let done, value, prevPosition;
  143. do {
  144. prevPosition = this.position;
  145. ( { done, value } = this.next() );
  146. } while ( !done && skip( value ) );
  147. if ( !done ) {
  148. this.position = prevPosition;
  149. }
  150. }
  151. /**
  152. * Gets the next tree walker's value.
  153. *
  154. * @returns {module:engine/view/treewalker~TreeWalkerValue} Object implementing iterator interface, returning
  155. * information about taken step.
  156. */
  157. next() {
  158. if ( this.direction == 'forward' ) {
  159. return this._next();
  160. } else {
  161. return this._previous();
  162. }
  163. }
  164. /**
  165. * Makes a step forward in view. Moves the {@link #position} to the next position and returns the encountered value.
  166. *
  167. * @private
  168. * @returns {Object}
  169. * @returns {Boolean} return.done `true` if iterator is done, `false` otherwise.
  170. * @returns {module:engine/view/treewalker~TreeWalkerValue} return.value Information about taken step.
  171. */
  172. _next() {
  173. let position = Position.createFromPosition( this.position );
  174. const previousPosition = this.position;
  175. const parent = position.parent;
  176. // We are at the end of the root.
  177. if ( parent.parent === null && position.offset === parent.childCount ) {
  178. return { done: true };
  179. }
  180. // We reached the walker boundary.
  181. if ( parent === this._boundaryEndParent && position.offset == this.boundaries.end.offset ) {
  182. return { done: true };
  183. }
  184. // Get node just after current position.
  185. let node;
  186. // Text is a specific parent because it contains string instead of child nodes.
  187. if ( parent instanceof Text ) {
  188. if ( position.isAtEnd ) {
  189. // Prevent returning "elementEnd" for Text node. Skip that value and return the next walker step.
  190. this.position = Position.createAfter( parent );
  191. return this._next();
  192. }
  193. node = parent.data[ position.offset ];
  194. } else {
  195. node = parent.getChild( position.offset );
  196. }
  197. if ( node instanceof Element ) {
  198. if ( !this.shallow ) {
  199. position = new Position( node, 0 );
  200. } else {
  201. position.offset++;
  202. }
  203. this.position = position;
  204. return this._formatReturnValue( 'elementStart', node, previousPosition, position, 1 );
  205. } else if ( node instanceof Text ) {
  206. if ( this.singleCharacters ) {
  207. position = new Position( node, 0 );
  208. this.position = position;
  209. return this._next();
  210. } else {
  211. let charactersCount = node.data.length;
  212. let item;
  213. // If text stick out of walker range, we need to cut it and wrap by TextProxy.
  214. if ( node == this._boundaryEndParent ) {
  215. charactersCount = this.boundaries.end.offset;
  216. item = new TextProxy( node, 0, charactersCount );
  217. position = Position.createAfter( item );
  218. } else {
  219. item = new TextProxy( node, 0, node.data.length );
  220. // If not just keep moving forward.
  221. position.offset++;
  222. }
  223. this.position = position;
  224. return this._formatReturnValue( 'text', item, previousPosition, position, charactersCount );
  225. }
  226. } else if ( typeof node == 'string' ) {
  227. let textLength;
  228. if ( this.singleCharacters ) {
  229. textLength = 1;
  230. } else {
  231. // Check if text stick out of walker range.
  232. const endOffset = parent === this._boundaryEndParent ? this.boundaries.end.offset : parent.data.length;
  233. textLength = endOffset - position.offset;
  234. }
  235. const textProxy = new TextProxy( parent, position.offset, textLength );
  236. position.offset += textLength;
  237. this.position = position;
  238. return this._formatReturnValue( 'text', textProxy, previousPosition, position, textLength );
  239. } else {
  240. // `node` is not set, we reached the end of current `parent`.
  241. position = Position.createAfter( parent );
  242. this.position = position;
  243. if ( this.ignoreElementEnd ) {
  244. return this._next();
  245. } else {
  246. return this._formatReturnValue( 'elementEnd', parent, previousPosition, position );
  247. }
  248. }
  249. }
  250. /**
  251. * Makes a step backward in view. Moves the {@link #position} to the previous position and returns the encountered value.
  252. *
  253. * @private
  254. * @returns {Object}
  255. * @returns {Boolean} return.done True if iterator is done.
  256. * @returns {module:engine/view/treewalker~TreeWalkerValue} return.value Information about taken step.
  257. */
  258. _previous() {
  259. let position = Position.createFromPosition( this.position );
  260. const previousPosition = this.position;
  261. const parent = position.parent;
  262. // We are at the beginning of the root.
  263. if ( parent.parent === null && position.offset === 0 ) {
  264. return { done: true };
  265. }
  266. // We reached the walker boundary.
  267. if ( parent == this._boundaryStartParent && position.offset == this.boundaries.start.offset ) {
  268. return { done: true };
  269. }
  270. // Get node just before current position.
  271. let node;
  272. // Text {@link module:engine/view/text~Text} element is a specific parent because contains string instead of child nodes.
  273. if ( parent instanceof Text ) {
  274. if ( position.isAtStart ) {
  275. // Prevent returning "elementStart" for Text node. Skip that value and return the next walker step.
  276. this.position = Position.createBefore( parent );
  277. return this._previous();
  278. }
  279. node = parent.data[ position.offset - 1 ];
  280. } else {
  281. node = parent.getChild( position.offset - 1 );
  282. }
  283. if ( node instanceof Element ) {
  284. if ( !this.shallow ) {
  285. position = new Position( node, node.childCount );
  286. this.position = position;
  287. if ( this.ignoreElementEnd ) {
  288. return this._previous();
  289. } else {
  290. return this._formatReturnValue( 'elementEnd', node, previousPosition, position );
  291. }
  292. } else {
  293. position.offset--;
  294. this.position = position;
  295. return this._formatReturnValue( 'elementStart', node, previousPosition, position, 1 );
  296. }
  297. } else if ( node instanceof Text ) {
  298. if ( this.singleCharacters ) {
  299. position = new Position( node, node.data.length );
  300. this.position = position;
  301. return this._previous();
  302. } else {
  303. let charactersCount = node.data.length;
  304. let item;
  305. // If text stick out of walker range, we need to cut it and wrap by TextProxy.
  306. if ( node == this._boundaryStartParent ) {
  307. const offset = this.boundaries.start.offset;
  308. item = new TextProxy( node, offset, node.data.length - offset );
  309. charactersCount = item.data.length;
  310. position = Position.createBefore( item );
  311. } else {
  312. item = new TextProxy( node, 0, node.data.length );
  313. // If not just keep moving backward.
  314. position.offset--;
  315. }
  316. this.position = position;
  317. return this._formatReturnValue( 'text', item, previousPosition, position, charactersCount );
  318. }
  319. } else if ( typeof node == 'string' ) {
  320. let textLength;
  321. if ( !this.singleCharacters ) {
  322. // Check if text stick out of walker range.
  323. const startOffset = parent === this._boundaryStartParent ? this.boundaries.start.offset : 0;
  324. textLength = position.offset - startOffset;
  325. } else {
  326. textLength = 1;
  327. }
  328. position.offset -= textLength;
  329. const textProxy = new TextProxy( parent, position.offset, textLength );
  330. this.position = position;
  331. return this._formatReturnValue( 'text', textProxy, previousPosition, position, textLength );
  332. } else {
  333. // `node` is not set, we reached the beginning of current `parent`.
  334. position = Position.createBefore( parent );
  335. this.position = position;
  336. return this._formatReturnValue( 'elementStart', parent, previousPosition, position, 1 );
  337. }
  338. }
  339. /**
  340. * Format returned data and adjust `previousPosition` and `nextPosition` if reach the bound of the {@link module:engine/view/text~Text}.
  341. *
  342. * @private
  343. * @param {module:engine/view/treewalker~TreeWalkerValueType} type Type of step.
  344. * @param {module:engine/view/item~Item} item Item between old and new position.
  345. * @param {module:engine/view/position~Position} previousPosition Previous position of iterator.
  346. * @param {module:engine/view/position~Position} nextPosition Next position of iterator.
  347. * @param {Number} [length] Length of the item.
  348. * @returns {module:engine/view/treewalker~TreeWalkerValue}
  349. */
  350. _formatReturnValue( type, item, previousPosition, nextPosition, length ) {
  351. // Text is a specific parent, because contains string instead of children.
  352. // Walker doesn't enter to the Text except situations when walker is iterating over every single character,
  353. // or the bound starts/ends inside the Text. So when the position is at the beginning or at the end of the Text
  354. // we move it just before or just after Text.
  355. if ( item instanceof TextProxy ) {
  356. // Position is at the end of Text.
  357. if ( item.offsetInText + item.data.length == item.textNode.data.length ) {
  358. if ( this.direction == 'forward' && !( this.boundaries && this.boundaries.end.isEqual( this.position ) ) ) {
  359. nextPosition = Position.createAfter( item.textNode );
  360. // When we change nextPosition of returned value we need also update walker current position.
  361. this.position = nextPosition;
  362. } else {
  363. previousPosition = Position.createAfter( item.textNode );
  364. }
  365. }
  366. // Position is at the begining ot the text.
  367. if ( item.offsetInText === 0 ) {
  368. if ( this.direction == 'backward' && !( this.boundaries && this.boundaries.start.isEqual( this.position ) ) ) {
  369. nextPosition = Position.createBefore( item.textNode );
  370. // When we change nextPosition of returned value we need also update walker current position.
  371. this.position = nextPosition;
  372. } else {
  373. previousPosition = Position.createBefore( item.textNode );
  374. }
  375. }
  376. }
  377. return {
  378. done: false,
  379. value: {
  380. type,
  381. item,
  382. previousPosition,
  383. nextPosition,
  384. length
  385. }
  386. };
  387. }
  388. }
  389. /**
  390. * Type of the step made by {@link module:engine/view/treewalker~TreeWalker}.
  391. * Possible values: `'elementStart'` if walker is at the beginning of a node, `'elementEnd'` if walker is at the end
  392. * of node, or `'text'` if walker traversed over single and multiple characters.
  393. * For {@link module:engine/view/text~Text} `elementStart` and `elementEnd` is not returned.
  394. *
  395. * @typedef {String} module:engine/view/treewalker~TreeWalkerValueType
  396. */
  397. /**
  398. * Object returned by {@link module:engine/view/treewalker~TreeWalker} when traversing tree view.
  399. *
  400. * @typedef {Object} module:engine/view/treewalker~TreeWalkerValue
  401. * @property {module:engine/view/treewalker~TreeWalkerValueType} type
  402. * @property {module:engine/view/item~Item} item Item between old and new positions of {@link module:engine/view/treewalker~TreeWalker}.
  403. * @property {module:engine/view/position~Position} previousPosition Previous position of the iterator.
  404. * * Forward iteration: For `'elementEnd'` it is the last position inside the element. For all other types it is the
  405. * position before the item. Note that it is more efficient to use this position then calculate the position before
  406. * the node using {@link module:engine/view/position~Position.createBefore}.
  407. * * Backward iteration: For `'elementStart'` it is the first position inside the element. For all other types it is
  408. * the position after item.
  409. * * If the position is at the beginning or at the end of the {@link module:engine/view/text~Text} it is always moved from the
  410. * inside of the Text to its parent just before or just after Text.
  411. * @property {module:engine/view/position~Position} nextPosition Next position of the iterator.
  412. * * Forward iteration: For `'elementStart'` it is the first position inside the element. For all other types it is
  413. * the position after the item.
  414. * * Backward iteration: For `'elementEnd'` it is last position inside element. For all other types it is the position
  415. * before the item.
  416. * * If the position is at the beginning or at the end of the {@link module:engine/view/text~Text} it is always moved from the
  417. * inside of the Text to its parent just before or just after Text.
  418. * @property {Number} [length] Length of the item. For `'elementStart'` it is 1. For `'text'` it is
  419. * the length of the text. For `'elementEnd'` it is undefined.
  420. */
  421. /**
  422. * Tree walking directions.
  423. *
  424. * @typedef {'forward'|'backward'} module:engine/view/treewalker~TreeWalkerDirection
  425. */