view.js 32 KB

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