view.js 33 KB

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