view.js 31 KB

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