treewalker.js 18 KB

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