view.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. /* jshint latedef:false */
  7. import ViewDocumentFragment from '/ckeditor5/engine/treeview/documentfragment.js';
  8. import HtmlDataProcessor from '/ckeditor5/engine/dataprocessor/htmldataprocessor.js';
  9. import ViewElement from '/ckeditor5/engine/treeview/element.js';
  10. import Selection from '/ckeditor5/engine/treeview/selection.js';
  11. import Range from '/ckeditor5/engine/treeview/range.js';
  12. import Position from '/ckeditor5/engine/treeview/position.js';
  13. import AttributeElement from '/ckeditor5/engine/treeview/attributeelement.js';
  14. import ContainerElement from '/ckeditor5/engine/treeview/containerelement.js';
  15. import ViewText from '/ckeditor5/engine/treeview/text.js';
  16. const DomDocumentFragment = window.DocumentFragment;
  17. const DomElement = window.Element;
  18. const ELEMENT_RANGE_START_TOKEN = '[';
  19. const ELEMENT_RANGE_END_TOKEN = ']';
  20. const TEXT_RANGE_START_TOKEN = '{';
  21. const TEXT_RANGE_END_TOKEN = '}';
  22. /**
  23. * Converts view elements to its HTML-like string representation.
  24. * Root element can be provided as {@link engine.treeView.Text Text}:
  25. *
  26. * const text = new Text( 'foobar' );
  27. * stringify( text ); // 'foobar'
  28. *
  29. * or as {@link engine.treeView.Element Element}:
  30. *
  31. * const element = new Element( 'p', null, new Text( 'foobar' ) );
  32. * stringify( element ); // '<p>foobar</p>'
  33. *
  34. * or as {@link engine.treeView.DocumentFragment DocumentFragment}:
  35. *
  36. * const text = new Text( 'foobar' );
  37. * const b = new Element( 'b', { name: 'test' }, text );
  38. * const p = new Element( 'p', { style: 'color:red;' } );
  39. * const fragment = new DocumentFragment( [ p, b ] );
  40. *
  41. * stringify( fragment ); // '<p style="color:red;"></p><b name="test">foobar</b>'
  42. *
  43. * Additionally {@link engine.treeView.Selection Selection} instance can be provided, then ranges from that selection
  44. * will be included in output data.
  45. * If range position is placed inside element node, it will be represented with `[` and `]`:
  46. *
  47. * const text = new Text( 'foobar' );
  48. * const b = new Element( 'b', null, text );
  49. * const p = new Element( 'p', null, b );
  50. * const selection = new Selection();
  51. * selection.addRange( Range.createFromParentsAndOffsets( p, 0, p, 1 ) );
  52. *
  53. * stringify( p, selection ); // <p>[<b>foobar</b>]</p>
  54. *
  55. * If range is placed inside text node, it will be represented with `{` and `}`:
  56. *
  57. * const text = new Text( 'foobar' );
  58. * const b = new Element( 'b', null, text );
  59. * const p = new Element( 'p', null, b );
  60. * const selection = new Selection();
  61. * selection.addRange( Range.createFromParentsAndOffsets( text, 1, text, 5 ) );
  62. *
  63. * stringify( p, selection ); // '<p><b>f{ooba}r</b></p>'
  64. *
  65. * Additional options object can be provided.
  66. * If `options.showType` is set to `true` element's types will be
  67. * presented for {@link engine.treeView.AttributeElement AttributeElements} and {@link engine.treeView.ContainerElement
  68. * ContainerElements}:
  69. *
  70. * const attribute = new AttributeElement( 'b' );
  71. * const container = new ContainerElement( 'p' );
  72. * getData( attribute, null, { showType: true } ); // '<attribute:b></attribute:b>'
  73. * getData( container, null, { showType: true } ); // '<container:p></container:p>'
  74. *
  75. * If `options.showPriority` is set to `true`, priority will be displayed for all
  76. * {@link engine.treeView.AttributeElement AttributeElements}.
  77. *
  78. * const attribute = new AttributeElement( 'b' );
  79. * attribute.priority = 20;
  80. * getData( attribute, null, { showPriority: true } ); // <b:20></b:20>
  81. *
  82. * @param {engine.treeView.Text|engine.treeView.Element|engine.treeView.DocumentFragment} node Node to stringify.
  83. * @param {engine.treeView.Selection} [selection = null ] Selection instance which ranges will be included in returned
  84. * string data.
  85. * @param {Object} [options] Object with additional options.
  86. * @param {Boolean} [options.showType=false] When set to `true` type of elements will be printed (`<container:p>`
  87. * instead of `<p>` and `<attribute:b>` instead of `<b>`).
  88. * @param {Boolean} [options.showPriority=false] When set to `true` AttributeElement's priority will be printed
  89. * (`<span:12>`, `<b:10>`).
  90. * @returns {String} HTML-like string representing the view.
  91. */
  92. export function stringify( node, selection = null, options = {} ) {
  93. const viewStringify = new ViewStringify( node, selection, options );
  94. return viewStringify.stringify();
  95. }
  96. /**
  97. * Parses HTML-like string and returns view tree nodes.
  98. * Simple string will be converted to {@link engine.treeView.Text Text} node:
  99. *
  100. * parse( 'foobar' ); // Returns instance of Text.
  101. *
  102. * {@link engine.treeView.Element Elements} will be parsed with attributes an children:
  103. *
  104. * parse( '<b name="baz">foobar</b>' ); // Returns instance of Element with `baz` attribute and text child node.
  105. *
  106. * Multiple nodes provided on root level will be converted to {@link engine.treeView.DocumentFragment DocumentFragment}:
  107. *
  108. * parse( '<b>foo</b><i>bar</i>' ); // Returns DocumentFragment with two child elements.
  109. *
  110. * Method can parse multiple {@link engine.treeView.Range ranges} provided in string data and return
  111. * {@link engine.treeView.Selection Selection} instance containing these ranges. Ranges placed inside
  112. * {@link engine.treeView.Text Text} nodes should be marked using `{` and `}` brackets:
  113. *
  114. * const { text, selection } = parse( 'f{ooba}r' );
  115. *
  116. * Ranges placed outside text nodes should be marked using `[` and `]` brackets:
  117. *
  118. * const { root, selection } = parse( '<p>[<b>foobar</b>]</p>' );
  119. *
  120. * Sometimes there is a need for defining order of ranges inside created selection. This can be achieved by providing
  121. * ranges order array as additional parameter:
  122. *
  123. * const { root, selection } = parse( '{fo}ob{ar}{ba}z', { order: [ 2, 3, 1 ] } );
  124. *
  125. * In above example first range (`{fo}`) will be added to selection as second one, second range (`{ar}`) will be added
  126. * as third and third range (`{ba}`) will be added as first one.
  127. *
  128. * If selection's last range should be added as backward one (so the {@link engine.treeView.Selection#anchor selection
  129. * anchor} is represented by `end` position and {@link engine.treeView.Selection#focus selection focus} is
  130. * represented by `start` position) use `lastRangeBackward` flag:
  131. *
  132. * const { root, selection } = parse( `{foo}bar{baz}`, { lastRangeBackward: true } );
  133. *
  134. * @param {String} data HTML-like string to be parsed.
  135. * @param {Object} options
  136. * @param {Array.<Number>} [options.order] Array with order of parsed ranges added to returned
  137. * {@link engine.treeView.Selection Selection} instance. Each element should represent desired position of each range in
  138. * selection instance. For example: `[2, 3, 1]` means that first range will be placed as second, second as third and third as first.
  139. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward to the returned
  140. * {@link engine.treeView.Selection Selection} instance.
  141. * @returns {engine.treeView.Text|engine.treeView.Element|engine.treeView.DocumentFragment|Object} Returns parsed view node
  142. * or object with two fields `view` and `selection` when selection ranges were included in data to parse.
  143. */
  144. export function parse( data, options = { } ) {
  145. options.order = options.order || [];
  146. const viewParser = new ViewParser();
  147. const rangeParser = new RangeParser();
  148. const view = viewParser.parse( data );
  149. const ranges = rangeParser.parse( view, options.order );
  150. // When ranges are present - return object containing view, and selection.
  151. if ( ranges.length ) {
  152. const selection = new Selection();
  153. selection.setRanges( ranges, !!options.lastRangeBackward );
  154. return {
  155. view: view,
  156. selection: selection
  157. };
  158. }
  159. return view;
  160. }
  161. /**
  162. * Private helper class used for converting ranges text representation inside {@link engine.treeView.Text Text nodes}.
  163. *
  164. * @private
  165. */
  166. class RangeParser {
  167. /**
  168. * Parses the view, and returns ranges represented inside {@link engine.treeView.Text Text nodes}.
  169. * Method will remove all occurrences of `{`, `}`, `[` and `]` from found text nodes. If text node is empty after
  170. * the process - it will be removed too.
  171. *
  172. * @param {engine.treeView.Node} node Starting node.
  173. * @param {Array.<Number>} order Ranges order. Each element should represent desired position of the range after
  174. * sorting. For example: `[2, 3, 1]` means that first range will be placed as second, second as third and third as first.
  175. * @returns {Array.<engine.treeView.Range>} Array with ranges found.
  176. */
  177. parse( node, order ) {
  178. this._positions = [];
  179. // Remove all range brackets from view nodes and save their positions.
  180. this._getPositions( node );
  181. // Create ranges using gathered positions.
  182. let ranges = this._createRanges();
  183. // Sort ranges if needed.
  184. if ( order.length ) {
  185. if ( order.length != ranges.length ) {
  186. throw new Error(
  187. `Parse error - there are ${ ranges.length} ranges found, but ranges order array contains ${ order.length } elements.`
  188. );
  189. }
  190. ranges = this._sortRanges( ranges, order );
  191. }
  192. return ranges;
  193. }
  194. /**
  195. * Gathers positions of brackets inside view tree starting from provided node. Method will remove all occurrences of
  196. * `{`, `}`, `[` and `]` from found text nodes. If text node is empty after the process - it will be removed
  197. * too.
  198. *
  199. * @private
  200. * @param {engine.treeView.Node} node Staring node.
  201. */
  202. _getPositions( node ) {
  203. if ( node instanceof ViewDocumentFragment || node instanceof ViewElement ) {
  204. // Copy elements into the array, when nodes will be removed from parent node this array will still have all the
  205. // items needed for iteration.
  206. const children = [ ...node.getChildren() ];
  207. for ( let child of children ) {
  208. this._getPositions( child );
  209. }
  210. }
  211. if ( node instanceof ViewText ) {
  212. const regexp = new RegExp(
  213. `[ ${TEXT_RANGE_START_TOKEN}${TEXT_RANGE_END_TOKEN}\\${ELEMENT_RANGE_END_TOKEN}\\${ELEMENT_RANGE_START_TOKEN} ]`,
  214. 'g'
  215. );
  216. let text = node.data;
  217. let match;
  218. let offset = 0;
  219. const brackets = [];
  220. // Remove brackets from text and store info about offset inside text node.
  221. while ( ( match = regexp.exec( text ) ) ) {
  222. const index = match.index;
  223. const bracket = match[ 0 ];
  224. brackets.push( {
  225. bracket: bracket,
  226. textOffset: index - offset
  227. } );
  228. offset++;
  229. }
  230. text = text.replace( regexp, '' );
  231. node.data = text;
  232. const index = node.getIndex();
  233. const parent = node.parent;
  234. // Remove empty text nodes.
  235. if ( !text ) {
  236. node.remove();
  237. }
  238. for ( let item of brackets ) {
  239. // Non-empty text node.
  240. if ( text ) {
  241. if ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) {
  242. // Store information about text range delimiter.
  243. this._positions.push( {
  244. bracket: item.bracket,
  245. position: new Position( node, item.textOffset )
  246. } );
  247. } else {
  248. // Check if element range delimiter is not placed inside text node.
  249. if ( item.textOffset !== 0 && item.textOffset !== text.length ) {
  250. throw new Error( `Parse error - range delimiter '${ item.bracket }' is placed inside text node.` );
  251. }
  252. // If bracket is placed at the end of the text node - it should be positioned after it.
  253. const offset = ( item.textOffset === 0 ? index : index + 1 );
  254. // Store information about element range delimiter.
  255. this._positions.push( {
  256. bracket: item.bracket,
  257. position: new Position( parent, offset )
  258. } );
  259. }
  260. } else {
  261. if ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) {
  262. throw new Error( `Parse error - text range delimiter '${ item.bracket }' is placed inside empty text node. ` );
  263. }
  264. // Store information about element range delimiter.
  265. this._positions.push( {
  266. bracket: item.bracket,
  267. position: new Position( parent, index )
  268. } );
  269. }
  270. }
  271. }
  272. }
  273. /**
  274. * Sort ranges in given order. Ranges order should be an array, each element should represent desired position
  275. * of the range after sorting.
  276. * For example: `[2, 3, 1]` means that first range will be placed as second, second as third and third as first.
  277. *
  278. * @private
  279. * @param {Array.<engine.treeView.Range>} ranges Ranges to sort.
  280. * @param {Array.<Number>} rangesOrder Array with new ranges order.
  281. * @returns {Array} Sorted ranges array.
  282. */
  283. _sortRanges( ranges, rangesOrder ) {
  284. const sortedRanges = [];
  285. let index = 0;
  286. for ( let newPosition of rangesOrder ) {
  287. if ( ranges[ newPosition - 1 ] === undefined ) {
  288. throw new Error( 'Parse error - provided ranges order is invalid.' );
  289. }
  290. sortedRanges[ newPosition - 1] = ranges[ index ];
  291. index++;
  292. }
  293. return sortedRanges;
  294. }
  295. /**
  296. * Uses all found bracket positions to create ranges from them.
  297. *
  298. * @private
  299. * @returns {Array.<engine.treeView.Range}
  300. */
  301. _createRanges() {
  302. const ranges = [];
  303. let range = null;
  304. for ( let item of this._positions ) {
  305. // When end of range is found without opening.
  306. if ( !range && ( item.bracket == ELEMENT_RANGE_END_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) ) {
  307. throw new Error( `Parse error - end of range was found '${ item.bracket }' but range was not started before.` );
  308. }
  309. // When second start of range is found when one is already opened - selection does not allow intersecting
  310. // ranges.
  311. if ( range && ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) ) {
  312. throw new Error( `Parse error - start of range was found '${ item.bracket }' but one range is already started.` );
  313. }
  314. if ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) {
  315. range = new Range( item.position, item.position );
  316. } else {
  317. range.end = item.position;
  318. ranges.push( range );
  319. range = null;
  320. }
  321. }
  322. // Check if all ranges have proper ending.
  323. if ( range !== null ) {
  324. throw new Error( 'Parse error - range was started but no end delimiter was found.' );
  325. }
  326. return ranges;
  327. }
  328. }
  329. /**
  330. * Private helper class used that converts given HTML-like string to view tree.
  331. *
  332. * @private
  333. */
  334. class ViewParser {
  335. /**
  336. * Parses HTML-like string to view tree elements.
  337. *
  338. * @param {string} data
  339. * @returns {engine.treeView.Node|engine.treeView.DocumentFragment}
  340. */
  341. parse( data ) {
  342. const htmlProcessor = new HtmlDataProcessor();
  343. // Convert HTML string to DOM.
  344. const domRoot = htmlProcessor.toDom( data );
  345. // Convert DOM to View.
  346. return this._walkDom( domRoot );
  347. }
  348. /**
  349. * Walks through DOM elements and converts them to tree view elements.
  350. *
  351. * @private
  352. * @param {Node} domNode
  353. * @returns {engine.treeView.Node|engine.treeView.DocumentFragment}
  354. */
  355. _walkDom( domNode ) {
  356. const isDomElement = domNode instanceof DomElement;
  357. if ( isDomElement || domNode instanceof DomDocumentFragment ) {
  358. const children = domNode.childNodes;
  359. const length = children.length;
  360. // If there is only one element inside DOM DocumentFragment - use it as root.
  361. if ( !isDomElement && length == 1 ) {
  362. return this._walkDom( domNode.childNodes[ 0 ] );
  363. }
  364. let viewElement;
  365. if ( isDomElement ) {
  366. viewElement = this._convertElement( domNode );
  367. } else {
  368. viewElement = new ViewDocumentFragment();
  369. }
  370. for ( let i = 0; i < children.length; i++ ) {
  371. const child = children[ i ];
  372. viewElement.appendChildren( this._walkDom( child ) );
  373. }
  374. return viewElement;
  375. }
  376. return new ViewText( domNode.textContent );
  377. }
  378. /**
  379. * Converts DOM Element to {engine.treeView.Element view Element}.
  380. *
  381. * @param {Element} domElement DOM element to convert.
  382. * @returns {engine.treeView.Element|engine.treeView.AttributeElement|engine.treeView.ContainerElement} Tree view
  383. * element converted from DOM element.
  384. * @private
  385. */
  386. _convertElement( domElement ) {
  387. const info = this._convertElementName( domElement );
  388. let viewElement;
  389. if ( info.type == 'attribute' ) {
  390. viewElement = new AttributeElement( info.name );
  391. if ( info.priority !== null ) {
  392. viewElement.priority = info.priority;
  393. }
  394. } else if ( info.type == 'container' ) {
  395. viewElement = new ContainerElement( info.name );
  396. } else {
  397. viewElement = new ViewElement( info.name );
  398. }
  399. const attributes = domElement.attributes;
  400. const attributesCount = attributes.length;
  401. for ( let i = 0; i < attributesCount; i++ ) {
  402. const attribute = attributes[ i ];
  403. viewElement.setAttribute( attribute.name, attribute.value );
  404. }
  405. return viewElement;
  406. }
  407. /**
  408. * Converts DOM element tag name to information needed for creating {@link engine.treeView.Element view Element} instance.
  409. * Name can be provided in couple formats: as a simple element's name (`div`), as a type and name (`container:div`,
  410. * `attribute:span`), as a name and priority (`span:12`) and as a type, priority, name trio (`attribute:span:12`);
  411. *
  412. * @private
  413. * @param {Element} element DOM Element which tag name should be converted.
  414. * @returns {Object} info Object with parsed information.
  415. * @returns {String} info.name Parsed name of the element.
  416. * @returns {String|null} info.type Parsed type of the element, can be `attribute` or `container`.
  417. * @returns {Number|null} info.priority Parsed priority of the element.
  418. */
  419. _convertElementName( element ) {
  420. const parts = element.tagName.toLowerCase().split( ':' );
  421. if ( parts.length == 1 ) {
  422. return {
  423. name: parts[ 0 ],
  424. type: null,
  425. priority: null
  426. };
  427. }
  428. if ( parts.length == 2 ) {
  429. // Check if type and name: container:div.
  430. const type = this._convertType( parts[ 0 ] );
  431. if ( type ) {
  432. return {
  433. name: parts[ 1 ],
  434. type: type,
  435. priority: null
  436. };
  437. }
  438. // Check if name and priority: span:10.
  439. const priority = this._convertPriority( parts[ 1 ] );
  440. if ( priority !== null ) {
  441. return {
  442. name: parts[ 0 ],
  443. type: 'attribute',
  444. priority: priority
  445. };
  446. }
  447. throw new Error( `Parse error - cannot parse element's tag name: ${ element.tagName.toLowerCase() }.` );
  448. }
  449. // Check if name is in format type:name:priority.
  450. if ( parts.length === 3 ) {
  451. const type = this._convertType( parts[ 0 ] );
  452. const priority = this._convertPriority( parts[ 2 ] );
  453. if ( type && priority !== null ) {
  454. return {
  455. name: parts[ 1 ],
  456. type: type,
  457. priority: priority
  458. };
  459. }
  460. }
  461. throw new Error( `Parse error - cannot parse element's tag name: ${ element.tagName.toLowerCase() }.` );
  462. }
  463. /**
  464. * Checks if element's type is allowed. Returns `attribute`, `container` or `null`.
  465. *
  466. * @private
  467. * @param {String} type
  468. * @returns {String|null}
  469. */
  470. _convertType( type ) {
  471. if ( type == 'container' || type == 'attribute' ) {
  472. return type;
  473. }
  474. return null;
  475. }
  476. /**
  477. * Checks if given priority is allowed. Returns null if priority cannot be converted.
  478. *
  479. * @private
  480. * @param {String} priorityString
  481. * @returns {Number|Null}
  482. */
  483. _convertPriority( priorityString ) {
  484. const priority = parseInt( priorityString, 10 );
  485. if ( !isNaN( priority ) ) {
  486. return priority;
  487. }
  488. return null;
  489. }
  490. }
  491. /**
  492. * Private helper class used for converting view tree to string.
  493. *
  494. * @private
  495. */
  496. class ViewStringify {
  497. /**
  498. * Creates ViewStringify instance.
  499. * @param root
  500. * @param {engine.treeView.Selection} [selection=null] Selection which ranges should be also converted to string.
  501. * @param {Object} [options] Options object.
  502. * @param {Boolean} [options.showType=false] When set to `true` type of elements will be printed ( `<container:p>`
  503. * instead of `<p>` and `<attribute:b>` instead of `<b>`.
  504. * @param {Boolean} [options.showPriority=false] When set to `true` AttributeElement's priority will be printed.
  505. */
  506. constructor( root, selection = null, options = {} ) {
  507. this.root = root;
  508. this.selection = selection;
  509. this.ranges = [];
  510. if ( this.selection ) {
  511. this.ranges = [ ...selection.getRanges() ];
  512. }
  513. this.showType = !!options.showType;
  514. this.showPriority = !!options.showPriority;
  515. }
  516. /**
  517. * Converts view to string.
  518. *
  519. * @returns {string} String representation of the view elements.
  520. */
  521. stringify() {
  522. let result = '';
  523. this._walkView( this.root, ( chunk ) => {
  524. result += chunk;
  525. } );
  526. return result;
  527. }
  528. /**
  529. * Executes simple walker that iterates over all elements in the view tree starting from root element.
  530. * Calls `callback` with parsed chunks of string data.
  531. *
  532. * @private
  533. * @param {engine.treeView.DocumentFragment|engine.treeView.Element|engine.treeView.Text} root
  534. * @param {Function} callback
  535. */
  536. _walkView( root, callback ) {
  537. const isElement = root instanceof ViewElement;
  538. if ( isElement || root instanceof ViewDocumentFragment ) {
  539. if ( isElement ) {
  540. callback( this._stringifyElementOpen( root ) );
  541. }
  542. let offset = 0;
  543. callback( this._stringifyElementRanges( root, offset ) );
  544. for ( let child of root.getChildren() ) {
  545. this._walkView( child, callback );
  546. offset++;
  547. callback( this._stringifyElementRanges( root, offset ) );
  548. }
  549. if ( isElement ) {
  550. callback( this._stringifyElementClose( root ) );
  551. }
  552. }
  553. if ( root instanceof ViewText ) {
  554. callback( this._stringifyTextRanges( root ) );
  555. }
  556. }
  557. /**
  558. * Checks if given {@link engine.treeView.Element Element} has {@link engine.treeView.Range#start range start} or
  559. * {@link engine.treeView.Range#start range end} placed at given offset and returns its string representation.
  560. *
  561. * @private
  562. * @param {engine.treeView.Element} element
  563. * @param {Number} offset
  564. */
  565. _stringifyElementRanges( element, offset ) {
  566. let start = '';
  567. let end = '';
  568. let collapsed = '';
  569. for ( let range of this.ranges ) {
  570. if ( range.start.parent == element && range.start.offset === offset ) {
  571. if ( range.isCollapsed ) {
  572. collapsed += ELEMENT_RANGE_START_TOKEN + ELEMENT_RANGE_END_TOKEN;
  573. } else {
  574. start += ELEMENT_RANGE_START_TOKEN;
  575. }
  576. }
  577. if ( range.end.parent === element && range.end.offset === offset && !range.isCollapsed ) {
  578. end += ELEMENT_RANGE_END_TOKEN;
  579. }
  580. }
  581. return end + collapsed + start;
  582. }
  583. /**
  584. * Checks if given {@link engine.treeView.Element Text node} has {@link engine.treeView.Range#start range start} or
  585. * {@link engine.treeView.Range#start range end} placed somewhere inside. Returns string representation of text
  586. * with range delimiters placed inside.
  587. *
  588. * @private
  589. * @param {engine.treeView.Text} node
  590. */
  591. _stringifyTextRanges( node ) {
  592. const length = node.data.length;
  593. let result = node.data.split( '' );
  594. // Add one more element for ranges ending after last character in text.
  595. result[ length ] = '';
  596. // Represent each letter as object with information about opening/closing ranges at each offset.
  597. result = result.map( ( letter ) => {
  598. return {
  599. letter: letter,
  600. start: '',
  601. end: '',
  602. collapsed: ''
  603. };
  604. } );
  605. for ( let range of this.ranges ) {
  606. const start = range.start;
  607. const end = range.end;
  608. if ( start.parent == node && start.offset >= 0 && start.offset <= length ) {
  609. if ( range.isCollapsed ) {
  610. result[ end.offset ].collapsed += TEXT_RANGE_START_TOKEN + TEXT_RANGE_END_TOKEN;
  611. } else {
  612. result[ start.offset ].start += TEXT_RANGE_START_TOKEN;
  613. }
  614. }
  615. if ( end.parent == node && end.offset >= 0 && end.offset <= length && !range.isCollapsed ) {
  616. result[ end.offset ].end += TEXT_RANGE_END_TOKEN;
  617. }
  618. }
  619. return result.map( item => item.end + item.collapsed + item.start + item.letter ).join( '' );
  620. }
  621. /**
  622. * Converts passed {@link engine.treeView.Element Element} to opening tag.
  623. * Depending on current configuration opening tag can be simple (`<a>`), contain type prefix (`<container:p>` or
  624. * `<attribute:a>`), contain priority information ( `<attribute:a priority=20>` ). Element's attributes also
  625. * will be included (`<a href="http://ckeditor.com" name="foobar">`).
  626. *
  627. * @private
  628. * @param {engine.treeView.Element} element
  629. * @returns {string}
  630. */
  631. _stringifyElementOpen( element ) {
  632. const priority = this._stringifyElementPriority( element );
  633. const type = this._stringifyElementType( element );
  634. const name = [ type, element.name, priority ].filter( i=> i !== '' ).join( ':' );
  635. const attributes = this._stringifyElementAttributes( element );
  636. const parts = [ name, attributes ];
  637. return `<${ parts.filter( i => i !== '' ).join( ' ' ) }>`;
  638. }
  639. /**
  640. * Converts passed {@link engine.treeView.Element Element} to closing tag.
  641. * Depending on current configuration opening tag can be simple (`</a>`) or contain type prefix (`</container:p>` or
  642. * `</attribute:a>`).
  643. *
  644. * @private
  645. * @param {engine.treeView.Element} element
  646. * @returns {string}
  647. */
  648. _stringifyElementClose( element ) {
  649. const priority = this._stringifyElementPriority( element );
  650. const type = this._stringifyElementType( element );
  651. const name = [ type, element.name, priority ].filter( i=> i !== '' ).join( ':' );
  652. return `</${ name }>`;
  653. }
  654. /**
  655. * Converts passed {@link engine.treeView.Element Element's} type to its string representation
  656. * Returns 'attribute' for {@link engine.treeView.AttributeElement AttributeElements} and
  657. * 'container' for {@link engine.treeView.ContainerElement ContainerElements}. Returns empty string when current
  658. * configuration is preventing showing elements' types.
  659. *
  660. * @private
  661. * @param {engine.treeView.Element} element
  662. * @returns {string}
  663. */
  664. _stringifyElementType( element ) {
  665. if ( this.showType ) {
  666. if ( element instanceof AttributeElement ) {
  667. return 'attribute';
  668. }
  669. if ( element instanceof ContainerElement ) {
  670. return 'container';
  671. }
  672. }
  673. return '';
  674. }
  675. /**
  676. * Converts passed {@link engine.treeView.Element Element} to its priority representation.
  677. * Priority string representation will be returned when passed element is an instance of
  678. * {@link engine.treeView.AttributeElement AttributeElement} and current configuration allow to show priority.
  679. * Otherwise returns empty string.
  680. *
  681. * @private
  682. * @param {engine.treeView.Element} element
  683. * @returns {string}
  684. */
  685. _stringifyElementPriority( element ) {
  686. if ( this.showPriority && element instanceof AttributeElement ) {
  687. return element.priority;
  688. }
  689. return '';
  690. }
  691. /**
  692. * Converts passed {@link engine.treeView.Element Element} attributes to their string representation.
  693. * If element has no attributes - empty string is returned.
  694. *
  695. * @private
  696. * @param {engine.treeView.Element} element
  697. * @returns {string}
  698. */
  699. _stringifyElementAttributes( element ) {
  700. const attributes = [];
  701. for ( let attribute of element.getAttributeKeys() ) {
  702. attributes.push( `${ attribute }="${ element.getAttribute( attribute ) }"` );
  703. }
  704. return attributes.join( ' ' );
  705. }
  706. }