8
0

view.js 32 KB

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