view.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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: view,
  314. selection: 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 ( let 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: 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 ( let item of brackets ) {
  411. // Non-empty text node.
  412. if ( text ) {
  413. if (
  414. this.sameSelectionCharacters ||
  415. ( !this.sameSelectionCharacters && ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) )
  416. ) {
  417. // Store information about text range delimiter.
  418. this._positions.push( {
  419. bracket: item.bracket,
  420. position: new Position( node, item.textOffset )
  421. } );
  422. } else {
  423. // Check if element range delimiter is not placed inside text node.
  424. if ( !this.sameSelectionCharacters && item.textOffset !== 0 && item.textOffset !== text.length ) {
  425. throw new Error( `Parse error - range delimiter '${ item.bracket }' is placed inside text node.` );
  426. }
  427. // If bracket is placed at the end of the text node - it should be positioned after it.
  428. const offset = ( item.textOffset === 0 ? index : index + 1 );
  429. // Store information about element range delimiter.
  430. this._positions.push( {
  431. bracket: item.bracket,
  432. position: new Position( parent, offset )
  433. } );
  434. }
  435. } else {
  436. if ( !this.sameSelectionCharacters && item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) {
  437. throw new Error( `Parse error - text range delimiter '${ item.bracket }' is placed inside empty text node. ` );
  438. }
  439. // Store information about element range delimiter.
  440. this._positions.push( {
  441. bracket: item.bracket,
  442. position: new Position( parent, index )
  443. } );
  444. }
  445. }
  446. }
  447. }
  448. /**
  449. * Sort ranges in given order. Ranges order should be an array, each element should represent desired position
  450. * of the range after sorting.
  451. * For example: `[2, 3, 1]` means that first range will be placed as second, second as third and third as first.
  452. *
  453. * @private
  454. * @param {Array.<module:engine/view/range~Range>} ranges Ranges to sort.
  455. * @param {Array.<Number>} rangesOrder Array with new ranges order.
  456. * @returns {Array} Sorted ranges array.
  457. */
  458. _sortRanges( ranges, rangesOrder ) {
  459. const sortedRanges = [];
  460. let index = 0;
  461. for ( let newPosition of rangesOrder ) {
  462. if ( ranges[ newPosition - 1 ] === undefined ) {
  463. throw new Error( 'Parse error - provided ranges order is invalid.' );
  464. }
  465. sortedRanges[ newPosition - 1 ] = ranges[ index ];
  466. index++;
  467. }
  468. return sortedRanges;
  469. }
  470. /**
  471. * Uses all found bracket positions to create ranges from them.
  472. *
  473. * @private
  474. * @returns {Array.<module:engine/view/range~Range>}
  475. */
  476. _createRanges() {
  477. const ranges = [];
  478. let range = null;
  479. for ( let item of this._positions ) {
  480. // When end of range is found without opening.
  481. if ( !range && ( item.bracket == ELEMENT_RANGE_END_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) ) {
  482. throw new Error( `Parse error - end of range was found '${ item.bracket }' but range was not started before.` );
  483. }
  484. // When second start of range is found when one is already opened - selection does not allow intersecting
  485. // ranges.
  486. if ( range && ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) ) {
  487. throw new Error( `Parse error - start of range was found '${ item.bracket }' but one range is already started.` );
  488. }
  489. if ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) {
  490. range = new Range( item.position, item.position );
  491. } else {
  492. range.end = item.position;
  493. ranges.push( range );
  494. range = null;
  495. }
  496. }
  497. // Check if all ranges have proper ending.
  498. if ( range !== null ) {
  499. throw new Error( 'Parse error - range was started but no end delimiter was found.' );
  500. }
  501. return ranges;
  502. }
  503. }
  504. /**
  505. * Private helper class used for converting view tree to string.
  506. *
  507. * @private
  508. */
  509. class ViewStringify {
  510. /**
  511. * Creates ViewStringify instance.
  512. *
  513. * @param root
  514. * @param {module:engine/view/selection~Selection} selection Selection which ranges should be also converted to string.
  515. * @param {Object} options Options object.
  516. * @param {Boolean} [options.showType=false] When set to `true` type of elements will be printed (`<container:p>`
  517. * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
  518. * @param {Boolean} [options.showPriority=false] When set to `true` AttributeElement's priority will be printed.
  519. * @param {Boolean} [options.ignoreRoot=false] When set to `true` root's element opening and closing tag will not
  520. * be outputted.
  521. * @param {Boolean} [options.sameSelectionCharacters=false] When set to `true` it means that selection inside text is marked as
  522. * `{` and `}` and selection outside text as `[` and `]`. When set to `false` then both are marked as `[` and `]`.
  523. */
  524. constructor( root, selection, options ) {
  525. this.root = root;
  526. this.selection = selection;
  527. this.ranges = [];
  528. if ( this.selection ) {
  529. this.ranges = [ ...selection.getRanges() ];
  530. }
  531. this.showType = !!options.showType;
  532. this.showPriority = !!options.showPriority;
  533. this.ignoreRoot = !!options.ignoreRoot;
  534. this.sameSelectionCharacters = !!options.sameSelectionCharacters;
  535. }
  536. /**
  537. * Converts view to string.
  538. *
  539. * @returns {String} String representation of the view elements.
  540. */
  541. stringify() {
  542. let result = '';
  543. this._walkView( this.root, ( chunk ) => {
  544. result += chunk;
  545. } );
  546. return result;
  547. }
  548. /**
  549. * Executes simple walker that iterates over all elements in the view tree starting from root element.
  550. * Calls `callback` with parsed chunks of string data.
  551. *
  552. * @private
  553. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element|module:engine/view/text~Text} root
  554. * @param {Function} callback
  555. */
  556. _walkView( root, callback ) {
  557. const ignore = this.ignoreRoot && this.root === root;
  558. if ( root.is( 'element' ) || root.is( 'documentFragment' ) ) {
  559. if ( root.is( 'element' ) && !ignore ) {
  560. callback( this._stringifyElementOpen( root ) );
  561. }
  562. let offset = 0;
  563. callback( this._stringifyElementRanges( root, offset ) );
  564. for ( let child of root.getChildren() ) {
  565. this._walkView( child, callback );
  566. offset++;
  567. callback( this._stringifyElementRanges( root, offset ) );
  568. }
  569. if ( root.is( 'element' ) && !ignore ) {
  570. callback( this._stringifyElementClose( root ) );
  571. }
  572. }
  573. if ( root.is( 'text' ) ) {
  574. callback( this._stringifyTextRanges( root ) );
  575. }
  576. }
  577. /**
  578. * Checks if given {@link module:engine/view/element~Element Element} has {@link module:engine/view/range~Range#start range start} or
  579. * {@link module:engine/view/range~Range#start range end} placed at given offset and returns its string representation.
  580. *
  581. * @private
  582. * @param {module:engine/view/element~Element} element
  583. * @param {Number} offset
  584. */
  585. _stringifyElementRanges( element, offset ) {
  586. let start = '';
  587. let end = '';
  588. let collapsed = '';
  589. for ( let range of this.ranges ) {
  590. if ( range.start.parent == element && range.start.offset === offset ) {
  591. if ( range.isCollapsed ) {
  592. collapsed += ELEMENT_RANGE_START_TOKEN + ELEMENT_RANGE_END_TOKEN;
  593. } else {
  594. start += ELEMENT_RANGE_START_TOKEN;
  595. }
  596. }
  597. if ( range.end.parent === element && range.end.offset === offset && !range.isCollapsed ) {
  598. end += ELEMENT_RANGE_END_TOKEN;
  599. }
  600. }
  601. return end + collapsed + start;
  602. }
  603. /**
  604. * Checks if given {@link module:engine/view/element~Element Text node} has {@link module:engine/view/range~Range#start range start} or
  605. * {@link module:engine/view/range~Range#start range end} placed somewhere inside. Returns string representation of text
  606. * with range delimiters placed inside.
  607. *
  608. * @private
  609. * @param {module:engine/view/text~Text} node
  610. */
  611. _stringifyTextRanges( node ) {
  612. const length = node.data.length;
  613. let result = node.data.split( '' );
  614. let rangeStartToken, rangeEndToken;
  615. if ( this.sameSelectionCharacters ) {
  616. rangeStartToken = ELEMENT_RANGE_START_TOKEN;
  617. rangeEndToken = ELEMENT_RANGE_END_TOKEN;
  618. } else {
  619. rangeStartToken = TEXT_RANGE_START_TOKEN;
  620. rangeEndToken = TEXT_RANGE_END_TOKEN;
  621. }
  622. // Add one more element for ranges ending after last character in text.
  623. result[ length ] = '';
  624. // Represent each letter as object with information about opening/closing ranges at each offset.
  625. result = result.map( ( letter ) => {
  626. return {
  627. letter: letter,
  628. start: '',
  629. end: '',
  630. collapsed: ''
  631. };
  632. } );
  633. for ( let range of this.ranges ) {
  634. const start = range.start;
  635. const end = range.end;
  636. if ( start.parent == node && start.offset >= 0 && start.offset <= length ) {
  637. if ( range.isCollapsed ) {
  638. result[ end.offset ].collapsed += rangeStartToken + rangeEndToken;
  639. } else {
  640. result[ start.offset ].start += rangeStartToken;
  641. }
  642. }
  643. if ( end.parent == node && end.offset >= 0 && end.offset <= length && !range.isCollapsed ) {
  644. result[ end.offset ].end += rangeEndToken;
  645. }
  646. }
  647. return result.map( item => item.end + item.collapsed + item.start + item.letter ).join( '' );
  648. }
  649. /**
  650. * Converts passed {@link module:engine/view/element~Element Element} to opening tag.
  651. * Depending on current configuration opening tag can be simple (`<a>`), contain type prefix (`<container:p>`,
  652. * `<attribute:a>` or `<empty:img>`), contain priority information ( `<attribute:a view-priority="20">` ).
  653. * Element's attributes also will be included (`<a href="http://ckeditor.com" name="foobar">`).
  654. *
  655. * @private
  656. * @param {module:engine/view/element~Element} element
  657. * @returns {String}
  658. */
  659. _stringifyElementOpen( element ) {
  660. const priority = this._stringifyElementPriority( element );
  661. const type = this._stringifyElementType( element );
  662. const name = [ type, element.name ].filter( i=> i !== '' ).join( ':' );
  663. const attributes = this._stringifyElementAttributes( element );
  664. const parts = [ name, priority, attributes ];
  665. return `<${ parts.filter( i => i !== '' ).join( ' ' ) }>`;
  666. }
  667. /**
  668. * Converts passed {@link module:engine/view/element~Element Element} to closing tag.
  669. * Depending on current configuration closing tag can be simple (`</a>`) or contain type prefix (`</container:p>`,
  670. * `</attribute:a>` or `</empty:img>`).
  671. *
  672. * @private
  673. * @param {module:engine/view/element~Element} element
  674. * @returns {String}
  675. */
  676. _stringifyElementClose( element ) {
  677. const type = this._stringifyElementType( element );
  678. const name = [ type, element.name ].filter( i=> i !== '' ).join( ':' );
  679. return `</${ name }>`;
  680. }
  681. /**
  682. * Converts passed {@link module:engine/view/element~Element Element's} type to its string representation
  683. *
  684. * Returns:
  685. * * 'attribute' for {@link module:engine/view/attributeelement~AttributeElement AttributeElements},
  686. * * 'container' for {@link module:engine/view/containerelement~ContainerElement ContainerElements},
  687. * * 'empty' for {@link module:engine/view/emptyelement~EmptyElement EmptyElements}.
  688. * * 'ui' for {@link module:engine/view/uielement~UIElement UIElements}.
  689. * * empty string when current configuration is preventing showing elements' types.
  690. *
  691. * @private
  692. * @param {module:engine/view/element~Element} element
  693. * @returns {String}
  694. */
  695. _stringifyElementType( element ) {
  696. if ( this.showType ) {
  697. for ( let type in allowedTypes ) {
  698. if ( element instanceof allowedTypes[ type ] ) {
  699. return type;
  700. }
  701. }
  702. }
  703. return '';
  704. }
  705. /**
  706. * Converts passed {@link module:engine/view/element~Element Element} to its priority representation.
  707. * Priority string representation will be returned when passed element is an instance of
  708. * {@link module:engine/view/attributeelement~AttributeElement AttributeElement} and current configuration allow to show priority.
  709. * Otherwise returns empty string.
  710. *
  711. * @private
  712. * @param {module:engine/view/element~Element} element
  713. * @returns {String}
  714. */
  715. _stringifyElementPriority( element ) {
  716. if ( this.showPriority && element.is( 'attributeElement' ) ) {
  717. return `view-priority="${ element.priority }"`;
  718. }
  719. return '';
  720. }
  721. /**
  722. * Converts passed {@link module:engine/view/element~Element Element} attributes to their string representation.
  723. * If element has no attributes - empty string is returned.
  724. *
  725. * @private
  726. * @param {module:engine/view/element~Element} element
  727. * @returns {String}
  728. */
  729. _stringifyElementAttributes( element ) {
  730. const attributes = [];
  731. const keys = [ ...element.getAttributeKeys() ].sort();
  732. for ( let attribute of keys ) {
  733. attributes.push( `${ attribute }="${ element.getAttribute( attribute ) }"` );
  734. }
  735. return attributes.join( ' ' );
  736. }
  737. }
  738. // Converts {@link module:engine/view/element~Element Elements} to
  739. // {@link module:engine/view/attributeelement~AttributeElement AttributeElements},
  740. // {@link module:engine/view/containerelement~ContainerElement ContainerElements},
  741. // {@link module:engine/view/emptyelement~EmptyElement EmptyElements} or
  742. // {@link module:engine/view/uielement~UIElement UIElements}.
  743. // It converts whole tree starting from the `rootNode`. Conversion is based on element names.
  744. // See `_convertElement` method for more details.
  745. //
  746. // @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|module:engine/view/text~Text}
  747. // rootNode Root node to convert.
  748. // @returns {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|
  749. // module:engine/view/text~Text} Root node of converted elements.
  750. function _convertViewElements( rootNode ) {
  751. if ( rootNode.is( 'element' ) || rootNode.is( 'documentFragment' ) ) {
  752. // Convert element or leave document fragment.
  753. const convertedElement = rootNode.is( 'documentFragment' ) ? new ViewDocumentFragment() : _convertElement( rootNode );
  754. // Convert all child nodes.
  755. for ( let child of rootNode.getChildren() ) {
  756. if ( convertedElement.is( 'emptyElement' ) ) {
  757. throw new Error( `Parse error - cannot parse inside EmptyElement.` );
  758. }
  759. if ( convertedElement.is( 'uiElement' ) ) {
  760. throw new Error( `Parse error - cannot parse inside UIElement.` );
  761. }
  762. convertedElement.appendChildren( _convertViewElements( child ) );
  763. }
  764. return convertedElement;
  765. }
  766. return rootNode;
  767. }
  768. // Converts {@link module:engine/view/element~Element Element} to
  769. // {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  770. // {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  771. // {@link module:engine/view/emptyelement~EmptyElement EmptyElement} or
  772. // {@link module:engine/view/uielement~UIElement UIElement}.
  773. // If element's name is in format `attribute:b` with `view-priority="11"` attribute it will be converted to
  774. // {@link module:engine/view/attributeelement~AttributeElement AttributeElement} with priority 11.
  775. // If element's name is in format `container:p` - it will be converted to
  776. // {@link module:engine/view/containerelement~ContainerElement ContainerElement}.
  777. // If element's name is in format `empty:img` - it will be converted to
  778. // {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
  779. // If element's name is in format `ui:span` - it will be converted to
  780. // {@link module:engine/view/uielement~UIElement UIElement}.
  781. // If element's name will not contain any additional information - {@link module:engine/view/element~Element view Element} will be
  782. // returned.
  783. //
  784. // @param {module:engine/view/element~Element} viewElement View element to convert.
  785. // @returns {module:engine/view/element~Element|module:engine/view/attributeelement~AttributeElement|
  786. // module:engine/view/emptyelement~EmptyElement|module:engine/view/uielement~UIElement|
  787. // module:engine/view/containerelement~ContainerElement} Tree view
  788. // element converted according to it's name.
  789. function _convertElement( viewElement ) {
  790. const info = _convertElementNameAndPriority( viewElement );
  791. const ElementConstructor = allowedTypes[ info.type ];
  792. const newElement = ElementConstructor ? new ElementConstructor( info.name ) : new ViewElement( info.name );
  793. if ( newElement.is( 'attributeElement' ) ) {
  794. if ( info.priority !== null ) {
  795. newElement.priority = info.priority;
  796. }
  797. }
  798. // Move attributes.
  799. for ( let attributeKey of viewElement.getAttributeKeys() ) {
  800. newElement.setAttribute( attributeKey, viewElement.getAttribute( attributeKey ) );
  801. }
  802. return newElement;
  803. }
  804. // Converts `view-priority` attribute and {@link module:engine/view/element~Element#name Element's name} information needed for creating
  805. // {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  806. // {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  807. // {@link module:engine/view/emptyelement~EmptyElement EmptyElement} or,
  808. // {@link module:engine/view/uielement~UIElement UIElement}.
  809. // Name can be provided in two formats: as a simple element's name (`div`), or as a type and name (`container:div`,
  810. // `attribute:span`, `empty:img`, `ui:span`);
  811. //
  812. // @param {module:engine/view/element~Element} element Element which name should be converted.
  813. // @returns {Object} info Object with parsed information.
  814. // @returns {String} info.name Parsed name of the element.
  815. // @returns {String|null} info.type Parsed type of the element, can be `attribute`, `container` or `empty`.
  816. // returns {Number|null} info.priority Parsed priority of the element.
  817. function _convertElementNameAndPriority( viewElement ) {
  818. const parts = viewElement.name.split( ':' );
  819. const priority = _convertPriority( viewElement.getAttribute( 'view-priority' ) );
  820. viewElement.removeAttribute( 'view-priority' );
  821. if ( parts.length == 1 ) {
  822. return {
  823. name: parts[ 0 ],
  824. type: priority !== null ? 'attribute' : null,
  825. priority: priority
  826. };
  827. }
  828. // Check if type and name: container:div.
  829. const type = _convertType( parts[ 0 ] );
  830. if ( type ) {
  831. return {
  832. name: parts[ 1 ],
  833. type: type,
  834. priority: priority
  835. };
  836. }
  837. throw new Error( `Parse error - cannot parse element's name: ${ viewElement.name }.` );
  838. }
  839. // Checks if element's type is allowed. Returns `attribute`, `container`, `empty` or `null`.
  840. //
  841. // @param {String} type
  842. // @returns {String|null}
  843. function _convertType( type ) {
  844. return allowedTypes[ type ] ? type : null;
  845. }
  846. // Checks if given priority is allowed. Returns null if priority cannot be converted.
  847. //
  848. // @param {String} priorityString
  849. // returns {Number|Null}
  850. function _convertPriority( priorityString ) {
  851. const priority = parseInt( priorityString, 10 );
  852. if ( !isNaN( priority ) ) {
  853. return priority;
  854. }
  855. return null;
  856. }