8
0

view.js 33 KB

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