view.js 27 KB

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