treewalker.js 15 KB

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