8
0

view.js 38 KB

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