8
0

view.js 27 KB

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