view.js 28 KB

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