treewalker.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 Element from './element.js';
  7. import Text from './text.js';
  8. import TextProxy from './textproxy.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.view
  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.view.Range} [options.boundaries=null] Range to define boundaries of the iterator.
  23. * @param {engine.view.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 engine.view.Text} should be returned as one {@link engine.view.Text} (`false`) ore one by one as
  27. * {@link engine.view.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 engine.view.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. 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 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 {engine.view.Range} engine.view.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 {engine.view.Position} engine.view.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.view.TreeWalker#direction
  79. */
  80. this.direction = options.direction || 'FORWARD';
  81. /**
  82. * Flag indicating whether all characters from {@link engine.view.Text} should be returned as one
  83. * {@link engine.view.Text} or one by one as {@link engine.view.TextProxy}.
  84. *
  85. * @readonly
  86. * @member {Boolean} engine.view.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} engine.view.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 engine.view.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} engine.view.TreeWalker#ignoreElementEnd
  104. */
  105. this.ignoreElementEnd = !!options.ignoreElementEnd;
  106. /**
  107. * Start boundary parent.
  108. *
  109. * @private
  110. * @member {engine.view.Node} engine.view.TreeWalker#_boundaryStartParent
  111. */
  112. this._boundaryStartParent = this.boundaries ? this.boundaries.start.parent : null;
  113. /**
  114. * End boundary parent.
  115. *
  116. * @private
  117. * @member {engine.view.Node} engine.view.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. * Iterator interface method.
  129. * Detects walking direction and makes step forward or backward.
  130. *
  131. * @returns {Object} Object implementing iterator interface, returning information about taken step.
  132. */
  133. next() {
  134. if ( this.direction == 'FORWARD' ) {
  135. return this._next();
  136. } else {
  137. return this._previous();
  138. }
  139. }
  140. /**
  141. * Makes a step forward in view. Moves the {@link #position} to the next position and returns the encountered value.
  142. *
  143. * @private
  144. * @returns {Object}
  145. * @returns {Boolean} return.done `true` if iterator is done, `false` otherwise.
  146. * @returns {engine.view.TreeWalkerValue} return.value Information about taken step.
  147. */
  148. _next() {
  149. let position = Position.createFromPosition( this.position );
  150. const previousPosition = this.position;
  151. const parent = position.parent;
  152. // We are at the end of the root.
  153. if ( parent.parent === null && position.offset === parent.getChildCount() ) {
  154. return { done: true };
  155. }
  156. // We reached the walker boundary.
  157. if ( parent === this._boundaryEndParent && position.offset == this.boundaries.end.offset ) {
  158. return { done: true };
  159. }
  160. // Get node just after current position.
  161. let node;
  162. // Text is a specific parent because it contains string instead of child nodes.
  163. if ( parent instanceof Text ) {
  164. node = parent.data[ position.offset ];
  165. } else {
  166. node = parent.getChild( position.offset );
  167. }
  168. if ( node instanceof Element ) {
  169. if ( !this.shallow ) {
  170. position = new Position( node, 0 );
  171. } else {
  172. position.offset++;
  173. }
  174. this.position = position;
  175. return this._formatReturnValue( 'elementStart', node, previousPosition, position, 1 );
  176. } else if ( node instanceof Text ) {
  177. if ( this.singleCharacters ) {
  178. position = new Position( node, 0 );
  179. this.position = position;
  180. return this._next();
  181. } else {
  182. let charactersCount = node.data.length;
  183. let item = node;
  184. // If text stick out of walker range, we need to cut it and wrap by TextProxy.
  185. if ( node == this._boundaryEndParent ) {
  186. charactersCount = this.boundaries.end.offset;
  187. item = new TextProxy( node, 0, charactersCount );
  188. position = Position.createAfter( item );
  189. } else {
  190. // If not just keep moving forward.
  191. position.offset++;
  192. }
  193. this.position = position;
  194. return this._formatReturnValue( 'TEXT', item, previousPosition, position, charactersCount );
  195. }
  196. } else if ( typeof node == 'string' ) {
  197. let textLength;
  198. if ( this.singleCharacters ) {
  199. textLength = 1;
  200. } else {
  201. // Check if text stick out of walker range.
  202. const endOffset = parent === this._boundaryEndParent ? this.boundaries.end.offset : parent.data.length;
  203. textLength = endOffset - position.offset;
  204. }
  205. const textProxy = new TextProxy( parent, position.offset, textLength );
  206. position.offset += textLength;
  207. this.position = position;
  208. return this._formatReturnValue( 'TEXT', textProxy, previousPosition, position, textLength );
  209. } else {
  210. // `node` is not set, we reached the end of current `parent`.
  211. position = Position.createAfter( parent );
  212. this.position = position;
  213. if ( this.ignoreElementEnd ) {
  214. return this._next();
  215. } else {
  216. return this._formatReturnValue( 'elementEnd', parent, previousPosition, position );
  217. }
  218. }
  219. }
  220. /**
  221. * Makes a step backward in view. Moves the {@link #position} to the previous position and returns the encountered value.
  222. *
  223. * @private
  224. * @returns {Object}
  225. * @returns {Boolean} return.done True if iterator is done.
  226. * @returns {engine.view.TreeWalkerValue} return.value Information about taken step.
  227. */
  228. _previous() {
  229. let position = Position.createFromPosition( this.position );
  230. const previousPosition = this.position;
  231. const parent = position.parent;
  232. // We are at the beginning of the root.
  233. if ( parent.parent === null && position.offset === 0 ) {
  234. return { done: true };
  235. }
  236. // We reached the walker boundary.
  237. if ( parent == this._boundaryStartParent && position.offset == this.boundaries.start.offset ) {
  238. return { done: true };
  239. }
  240. // Get node just before current position.
  241. let node;
  242. // Text {@link engine.view.Text} element is a specific parent because contains string instead of child nodes.
  243. if ( parent instanceof Text ) {
  244. node = parent.data[ position.offset - 1 ];
  245. } else {
  246. node = parent.getChild( position.offset - 1 );
  247. }
  248. if ( node instanceof Element ) {
  249. if ( !this.shallow ) {
  250. position = new Position( node, node.getChildCount() );
  251. this.position = position;
  252. if ( this.ignoreElementEnd ) {
  253. return this._previous();
  254. } else {
  255. return this._formatReturnValue( 'elementEnd', node, previousPosition, position );
  256. }
  257. } else {
  258. position.offset--;
  259. this.position = position;
  260. return this._formatReturnValue( 'elementStart', node, previousPosition, position, 1 );
  261. }
  262. } else if ( node instanceof Text ) {
  263. if ( this.singleCharacters ) {
  264. position = new Position( node, node.data.length );
  265. this.position = position;
  266. return this._previous();
  267. } else {
  268. let charactersCount = node.data.length;
  269. let item = node;
  270. // If text stick out of walker range, we need to cut it and wrap by TextProxy.
  271. if ( node == this._boundaryStartParent ) {
  272. const offset = this.boundaries.start.offset;
  273. item = new TextProxy( node, offset );
  274. charactersCount = item.data.length;
  275. position = Position.createBefore( item );
  276. } else {
  277. // If not just keep moving backward.
  278. position.offset--;
  279. }
  280. this.position = position;
  281. return this._formatReturnValue( 'TEXT', item, previousPosition, position, charactersCount );
  282. }
  283. } else if ( typeof node == 'string' ) {
  284. let textLength;
  285. if ( !this.singleCharacters ) {
  286. // Check if text stick out of walker range.
  287. const startOffset = parent === this._boundaryStartParent ? this.boundaries.start.offset : 0;
  288. textLength = position.offset - startOffset;
  289. } else {
  290. textLength = 1;
  291. }
  292. position.offset -= textLength;
  293. const textProxy = new TextProxy( parent, position.offset, textLength );
  294. this.position = position;
  295. return this._formatReturnValue( 'TEXT', textProxy, previousPosition, position, textLength );
  296. } else {
  297. // `node` is not set, we reached the beginning of current `parent`.
  298. position = Position.createBefore( parent );
  299. this.position = position;
  300. return this._formatReturnValue( 'elementStart', parent, previousPosition, position, 1 );
  301. }
  302. }
  303. /**
  304. * Format returned data and adjust `previousPosition` and `nextPosition` if reach the bound of the {@link engine.view.Text}.
  305. *
  306. * @private
  307. * @param {engine.view.TreeWalkerValueType} type Type of step.
  308. * @param {engine.view.Item} item Item between old and new position.
  309. * @param {engine.view.Position} previousPosition Previous position of iterator.
  310. * @param {engine.view.Position} nextPosition Next position of iterator.
  311. * @param {Number} [length] Length of the item.
  312. * @returns {engine.view.TreeWalkerValue}
  313. */
  314. _formatReturnValue( type, item, previousPosition, nextPosition, length ) {
  315. // Text is a specific parent, because contains string instead of childs.
  316. // Walker doesn't enter to the Text except situations when walker is iterating over every single character,
  317. // or the bound starts/ends inside the Text. So when the position is at the beginning or at the end of the Text
  318. // we move it just before or just after Text.
  319. if ( item instanceof TextProxy ) {
  320. // Position is at the end of Text.
  321. if ( item.index + item.data.length == item.textNode.data.length ) {
  322. if ( this.direction == 'FORWARD' ) {
  323. nextPosition = Position.createAfter( item.textNode );
  324. // When we change nextPosition of returned value we need also update walker current position.
  325. this.position = nextPosition;
  326. } else {
  327. previousPosition = Position.createAfter( item.textNode );
  328. }
  329. }
  330. // Position is at the begining ot the text.
  331. if ( item.index === 0 ) {
  332. if ( this.direction == 'FORWARD' ) {
  333. previousPosition = Position.createBefore( item.textNode );
  334. } else {
  335. nextPosition = Position.createBefore( item.textNode );
  336. // When we change nextPosition of returned value we need also update walker current position.
  337. this.position = nextPosition;
  338. }
  339. }
  340. }
  341. return {
  342. done: false,
  343. value: {
  344. type: type,
  345. item: item,
  346. previousPosition: previousPosition,
  347. nextPosition: nextPosition,
  348. length: length
  349. }
  350. };
  351. }
  352. }
  353. /**
  354. * Type of the step made by {@link engine.view.TreeWalker}.
  355. * Possible values: `'elementStart'` if walker is at the beginning of a node, `'elementEnd'` if walker is at the end
  356. * of node, or `'TEXT'` if walker traversed over single and multiple characters.
  357. * For {@link engine.view.Text} `elementStart` and `elementEnd` is not returned.
  358. *
  359. * @typedef {String} engine.view.TreeWalkerValueType
  360. */
  361. /**
  362. * Object returned by {@link engine.view.TreeWalker} when traversing tree view.
  363. *
  364. * @typedef {Object} engine.view.TreeWalkerValue
  365. * @property {engine.view.TreeWalkerValueType} type
  366. * @property {engine.view.Item} item Item between old and new positions of {@link engine.view.TreeWalker}.
  367. * @property {engine.view.Position} previousPosition Previous position of the iterator.
  368. * * Forward iteration: For `'elementEnd'` it is the last position inside the element. For all other types it is the
  369. * position before the item. Note that it is more efficient to use this position then calculate the position before
  370. * the node using {@link engine.view.Position.createBefore}.
  371. * * Backward iteration: For `'elementStart'` it is the first position inside the element. For all other types it is
  372. * the position after item.
  373. * * If the position is at the beginning or at the end of the {@link engine.view.Text} it is always moved from the
  374. * inside of the Text to its parent just before or just after Text.
  375. * @property {engine.view.Position} nextPosition Next position of the iterator.
  376. * * Forward iteration: For `'elementStart'` it is the first position inside the element. For all other types it is
  377. * the position after the item.
  378. * * Backward iteration: For `'elementEnd'` it is last position inside element. For all other types it is the position
  379. * before the item.
  380. * * If the position is at the beginning or at the end of the {@link engine.view.Text} it is always moved from the
  381. * inside of the Text to its parent just before or just after Text.
  382. * @property {Number} [length] Length of the item. For `'elementStart'` it is 1. For `'TEXT'` it is
  383. * the length of the text. For `'elementEnd'` it is undefined.
  384. */
  385. /**
  386. * Tree walking directions.
  387. *
  388. * @typedef {'FORWARD'|'BACKWARD'} engine.view.TreeWalkerDirection
  389. */