view.js 37 KB

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