view.js 30 KB

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