8
0

view.js 27 KB

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