view.js 32 KB

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