view.js 38 KB

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