treewalker.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 `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.view.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 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.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 `ELEMENT_END` 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 `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.view.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.view.TreeWalker#ignoreElementEnd
  105. */
  106. this.ignoreElementEnd = !!options.ignoreElementEnd;
  107. /**
  108. * Start boundary cached for optimization purposes.
  109. *
  110. * @private
  111. * @member {engine.view.Element} engine.view.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.view.Element} engine.view.TreeWalker#_boundaryEndParent
  119. */
  120. this._boundaryEndParent = this.boundaries ? this.boundaries.end.parent : null;
  121. }
  122. /**
  123. * Iterator interface.
  124. */
  125. [ Symbol.iterator ]() {
  126. return this;
  127. }
  128. /**
  129. * Iterator interface method.
  130. * Detects walking direction and makes step forward or backward.
  131. *
  132. * @returns {Object} Object implementing iterator interface, returning information about taken step.
  133. */
  134. next() {
  135. if ( this.direction == 'FORWARD' ) {
  136. return this._next();
  137. } else {
  138. return this._previous();
  139. }
  140. }
  141. /**
  142. * Makes a step forward in view. Moves the {@link #position} to the next position and returns the encountered value.
  143. *
  144. * @private
  145. * @returns {Object}
  146. * @returns {Boolean} return.done True if iterator is done.
  147. * @returns {engine.view.TreeWalkerValue} return.value Information about taken step.
  148. */
  149. _next() {
  150. let position = Position.createFromPosition( this.position );
  151. const previousPosition = this.position;
  152. const parent = position.parent;
  153. // We are at the end of the root.
  154. if ( parent.parent === null && position.offset === parent.getChildCount() ) {
  155. return { done: true };
  156. }
  157. // We reached the walker boundary.
  158. if ( parent === this._boundaryEndParent && position.offset == this.boundaries.end.offset ) {
  159. return { done: true };
  160. }
  161. // Get node just after current position.
  162. let node;
  163. // Text {@link engine.view.Text} element is a specific parent because it contains string instead of child nodes.
  164. if ( parent instanceof Text ) {
  165. node = parent._data[ position.offset ];
  166. } else {
  167. node = parent.getChild( position.offset );
  168. }
  169. if ( node instanceof Element ) {
  170. if ( !this.shallow ) {
  171. position = new Position( node, 0 );
  172. } else {
  173. position.offset++;
  174. }
  175. this.position = position;
  176. return formatReturnValue( 'ELEMENT_START', node, previousPosition, position, 1 );
  177. } else if ( node instanceof Text ) {
  178. if ( this.singleCharacters ) {
  179. position = new Position( node, 0 );
  180. this.position = position;
  181. return this._next();
  182. } else {
  183. let charactersCount = node._data.length;
  184. let item = node;
  185. // If text stick out of walker range, we need to cut it.
  186. if ( node == this._boundaryEndParent ) {
  187. const offset = this.boundaries.end.offset;
  188. const textFragment = node._data.substring( 0, offset );
  189. charactersCount = textFragment.length;
  190. item = new TextProxy( textFragment, node.parent, node, 0 );
  191. position = Position.createAfter( item );
  192. } else {
  193. // If not just move forward.
  194. position.offset++;
  195. }
  196. this.position = position;
  197. return formatReturnValue( 'TEXT', item, previousPosition, position, charactersCount );
  198. }
  199. } else if ( typeof node == 'string' ) {
  200. position.offset++;
  201. const textProxy = new TextProxy( node, parent.parent, parent, position.offset );
  202. this.position = position;
  203. return formatReturnValue( 'TEXT', textProxy, previousPosition, position, 1 );
  204. } else {
  205. // `node` is not set, we reached the end of current `parent`.
  206. position = Position.createAfter( parent );
  207. this.position = position;
  208. // We don't return `ELEMENT_END` for {@link engine.view.Text} element.
  209. if ( this.ignoreElementEnd || parent instanceof Text ) {
  210. return this._next();
  211. } else {
  212. return formatReturnValue( 'ELEMENT_END', parent, previousPosition, position );
  213. }
  214. }
  215. }
  216. /**
  217. * Makes a step backward in view. Moves the {@link #position} to the previous position and returns the encountered value.
  218. *
  219. * @private
  220. * @returns {Object}
  221. * @returns {Boolean} return.done True if iterator is done.
  222. * @returns {engine.view.TreeWalkerValue} return.value Information about taken step.
  223. */
  224. _previous() {
  225. let position = Position.createFromPosition( this.position );
  226. const previousPosition = this.position;
  227. const parent = position.parent;
  228. // We are at the beginning of the root.
  229. if ( parent.parent === null && position.offset === 0 ) {
  230. return { done: true };
  231. }
  232. // We reached the walker boundary.
  233. if ( parent == this._boundaryStartParent && position.offset == this.boundaries.start.offset ) {
  234. return { done: true };
  235. }
  236. // Get node just before current position.
  237. let node;
  238. // Text {@link engine.view.Text} element is a specific parent because contains string instead of child nodes.
  239. if ( parent instanceof Text ) {
  240. node = parent._data[ position.offset - 1 ];
  241. } else {
  242. node = parent.getChild( position.offset - 1 );
  243. }
  244. if ( node instanceof Element ) {
  245. if ( !this.shallow ) {
  246. position = new Position( node, node.getChildCount() );
  247. this.position = position;
  248. if ( this.ignoreElementEnd ) {
  249. return this._previous();
  250. } else {
  251. return formatReturnValue( 'ELEMENT_END', node, previousPosition, position );
  252. }
  253. } else {
  254. position.offset--;
  255. this.position = position;
  256. return formatReturnValue( 'ELEMENT_START', node, previousPosition, position, 1 );
  257. }
  258. } else if ( node instanceof Text ) {
  259. if ( this.singleCharacters ) {
  260. position = new Position( node, node._data.length );
  261. this.position = position;
  262. return this._previous();
  263. } else {
  264. let charactersCount = node._data.length;
  265. let item = node;
  266. // If text stick out of walker range, we need to cut it.
  267. if ( node == this._boundaryStartParent ) {
  268. const offset = this.boundaries.start.offset;
  269. const textFragment = node._data.substring( offset, charactersCount );
  270. charactersCount = textFragment.length;
  271. item = new TextProxy( textFragment, node.parent, node, offset );
  272. position = Position.createBefore( item );
  273. } else {
  274. // If not just move backward.
  275. position.offset--;
  276. }
  277. this.position = position;
  278. return formatReturnValue( 'TEXT', item, previousPosition, position, charactersCount );
  279. }
  280. } else if ( typeof node == 'string' ) {
  281. position.offset--;
  282. const textProxy = new TextProxy( node, parent.parent, parent, position.offset );
  283. this.position = position;
  284. return formatReturnValue( 'TEXT', textProxy, previousPosition, position, 1 );
  285. } else {
  286. // `node` is not set, we reached the beginning of current `parent`.
  287. position = Position.createBefore( parent );
  288. this.position = position;
  289. // We don't return `ELEMENT_START` for {@link engine.view.Text} element.
  290. if ( parent instanceof Text ) {
  291. return this._previous();
  292. }
  293. return formatReturnValue( 'ELEMENT_START', parent, previousPosition, position, 1 );
  294. }
  295. }
  296. }
  297. function formatReturnValue( type, item, previousPosition, nextPosition, length ) {
  298. return {
  299. done: false,
  300. value: {
  301. type: type,
  302. item: item,
  303. previousPosition: previousPosition,
  304. nextPosition: nextPosition,
  305. length: length
  306. }
  307. };
  308. }
  309. /**
  310. * Type of the step made by {@link engine.view.TreeWalker}.
  311. * Possible values: `'ELEMENT_START'` if walker is at the beginning of a node, `'ELEMENT_END'` if walker is at the end
  312. * of node, or `'TEXT'` if walker traversed over single and multiple characters.
  313. *
  314. * @typedef {String} engine.view.TreeWalkerValueType
  315. */
  316. /**
  317. * Object returned by {@link engine.view.TreeWalker} when traversing tree view.
  318. *
  319. * @typedef {Object} engine.view.TreeWalkerValue
  320. * @property {engine.view.TreeWalkerValueType} type
  321. * @property {engine.view.Item} item Item between old and new positions of {@link engine.view.TreeWalker}.
  322. * @property {engine.view.Position} previousPosition Previous position of the iterator.
  323. * * Forward iteration: For `'ELEMENT_END'` it is the last position inside the element. For all other types it is the
  324. * position before the item. Note that it is more efficient to use this position then calculate the position before
  325. * the node using {@link engine.view.Position.createBefore}.
  326. * * Backward iteration: For `'ELEMENT_START'` it is the first position inside the element. For all other types it is
  327. * the position after item.
  328. * @property {engine.view.Position} nextPosition Next position of the iterator.
  329. * * Forward iteration: For `'ELEMENT_START'` it is the first position inside the element. For all other types it is
  330. * the position after the item.
  331. * * Backward iteration: For `'ELEMENT_END'` it is last position inside element. For all other types it is the position
  332. * before the item.
  333. * @property {Number} [length] Length of the item. For `'ELEMENT_START'` it is 1. For `'TEXT'` it is
  334. * the length of the text. For `'ELEMENT_END'` it is undefined.
  335. */
  336. /**
  337. * Tree walking directions.
  338. *
  339. * @typedef {'FORWARD'|'BACKWARD'} engine.view.TreeWalkerDirection
  340. */