view.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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 DocumentSelection from '../view/documentselection';
  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/documentselection~DocumentSelection selection} instance can be provided.
  113. * Ranges from the selection 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/documentselection~DocumentSelection selection} instance. If a range instance
  151. * is provided, it will be converted to a selection containing this range. If a position instance is provided, it will
  152. * be converted to a selection 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/documentselection~DocumentSelection|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 DocumentSelection( 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/documentselection~DocumentSelection 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
  253. * (so the {@link module:engine/view/documentselection~DocumentSelection#anchor selection anchor} is represented
  254. * by the `end` position and {@link module:engine/view/documentselection~DocumentSelection#focus selection focus} is
  255. * represented by the `start` position), use the `lastRangeBackward` flag:
  256. *
  257. * const { root, selection } = parse( `{foo}bar{baz}`, { lastRangeBackward: true } );
  258. *
  259. * Some more examples and edge cases:
  260. *
  261. * // Returns an empty document fragment.
  262. * parse( '' );
  263. *
  264. * // Returns an empty document fragment and a collapsed selection.
  265. * const { root, selection } = parse( '[]' );
  266. *
  267. * // Returns an element and a selection that is placed inside the document fragment containing that element.
  268. * const { root, selection } = parse( '[<a></a>]' );
  269. *
  270. * @param {String} data An HTML-like string to be parsed.
  271. * @param {Object} options
  272. * @param {Array.<Number>} [options.order] An array with the order of parsed ranges added to the returned
  273. * {@link module:engine/view/documentselection~DocumentSelection Selection} instance. Each element should represent the
  274. * desired position of each range in the selection instance. For example: `[2, 3, 1]` means that the first range will be
  275. * placed as the second, the second as the third and the third as the first.
  276. * @param {Boolean} [options.lastRangeBackward=false] If set to `true`, the last range will be added as backward to the returned
  277. * {@link module:engine/view/documentselection~DocumentSelection selection} instance.
  278. * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment}
  279. * [options.rootElement=null] The default root to use when parsing elements.
  280. * When set to `null`, the root element will be created automatically. If set to
  281. * {@link module:engine/view/element~Element Element} or {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment},
  282. * this node will be used as the root for all parsed nodes.
  283. * @param {Boolean} [options.sameSelectionCharacters=false] When set to `false`, the selection inside the text should be marked using
  284. * `{` and `}` and the selection outside the ext using `[` and `]`. When set to `true`, both should be marked with `[` and `]` only.
  285. * @returns {module:engine/view/text~Text|module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|Object}
  286. * Returns the parsed view node or an object with two fields: `view` and `selection` when selection ranges were included in the data
  287. * to parse.
  288. */
  289. export function parse( data, options = {} ) {
  290. options.order = options.order || [];
  291. const rangeParser = new RangeParser( {
  292. sameSelectionCharacters: options.sameSelectionCharacters
  293. } );
  294. const processor = new XmlDataProcessor( {
  295. namespaces: Object.keys( allowedTypes )
  296. } );
  297. // Convert data to view.
  298. let view = processor.toView( data );
  299. // At this point we have a view tree with Elements that could have names like `attribute:b:1`. In the next step
  300. // we need to parse Element's names and convert them to AttributeElements and ContainerElements.
  301. view = _convertViewElements( view );
  302. // If custom root is provided - move all nodes there.
  303. if ( options.rootElement ) {
  304. const root = options.rootElement;
  305. const nodes = view._removeChildren( 0, view.childCount );
  306. root._removeChildren( 0, root.childCount );
  307. root._appendChildren( nodes );
  308. view = root;
  309. }
  310. // Parse ranges included in view text nodes.
  311. const ranges = rangeParser.parse( view, options.order );
  312. // If only one element is returned inside DocumentFragment - return that element.
  313. if ( view.is( 'documentFragment' ) && view.childCount === 1 ) {
  314. view = view.getChild( 0 );
  315. }
  316. // When ranges are present - return object containing view, and selection.
  317. if ( ranges.length ) {
  318. const selection = new DocumentSelection( ranges, { backward: !!options.lastRangeBackward } );
  319. return {
  320. view,
  321. selection
  322. };
  323. }
  324. // If single element is returned without selection - remove it from parent and return detached element.
  325. if ( view.parent ) {
  326. view._remove();
  327. }
  328. return view;
  329. }
  330. /**
  331. * Private helper class used for converting ranges represented as text inside view {@link module:engine/view/text~Text text nodes}.
  332. *
  333. * @private
  334. */
  335. class RangeParser {
  336. /**
  337. * Creates a range parser instance.
  338. *
  339. * @param {Object} options The range parser configuration.
  340. * @param {Boolean} [options.sameSelectionCharacters=false] When set to `true`, the selection inside the text is marked as
  341. * `{` and `}` and the selection outside the text as `[` and `]`. When set to `false`, both are marked as `[` and `]`.
  342. */
  343. constructor( options ) {
  344. this.sameSelectionCharacters = !!options.sameSelectionCharacters;
  345. }
  346. /**
  347. * Parses the view and returns ranges represented inside {@link module:engine/view/text~Text text nodes}.
  348. * The method will remove all occurrences of `{`, `}`, `[` and `]` from found text nodes. If a text node is empty after
  349. * the process, it will be removed, too.
  350. *
  351. * @param {module:engine/view/node~Node} node The starting node.
  352. * @param {Array.<Number>} order The order of ranges. Each element should represent the desired position of the range after
  353. * 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
  354. * as the first.
  355. * @returns {Array.<module:engine/view/range~Range>} An array with ranges found.
  356. */
  357. parse( node, order ) {
  358. this._positions = [];
  359. // Remove all range brackets from view nodes and save their positions.
  360. this._getPositions( node );
  361. // Create ranges using gathered positions.
  362. let ranges = this._createRanges();
  363. // Sort ranges if needed.
  364. if ( order.length ) {
  365. if ( order.length != ranges.length ) {
  366. throw new Error(
  367. `Parse error - there are ${ ranges.length } ranges found, but ranges order array contains ${ order.length } elements.`
  368. );
  369. }
  370. ranges = this._sortRanges( ranges, order );
  371. }
  372. return ranges;
  373. }
  374. /**
  375. * Gathers positions of brackets inside the view tree starting from the provided node. The method will remove all occurrences of
  376. * `{`, `}`, `[` and `]` from found text nodes. If a text node is empty after the process, it will be removed, too.
  377. *
  378. * @private
  379. * @param {module:engine/view/node~Node} node Staring node.
  380. */
  381. _getPositions( node ) {
  382. if ( node.is( 'documentFragment' ) || node.is( 'element' ) ) {
  383. // Copy elements into the array, when nodes will be removed from parent node this array will still have all the
  384. // items needed for iteration.
  385. const children = [ ...node.getChildren() ];
  386. for ( const child of children ) {
  387. this._getPositions( child );
  388. }
  389. }
  390. if ( node.is( 'text' ) ) {
  391. const regexp = new RegExp(
  392. `[${ TEXT_RANGE_START_TOKEN }${ TEXT_RANGE_END_TOKEN }\\${ ELEMENT_RANGE_END_TOKEN }\\${ ELEMENT_RANGE_START_TOKEN }]`,
  393. 'g'
  394. );
  395. let text = node.data;
  396. let match;
  397. let offset = 0;
  398. const brackets = [];
  399. // Remove brackets from text and store info about offset inside text node.
  400. while ( ( match = regexp.exec( text ) ) ) {
  401. const index = match.index;
  402. const bracket = match[ 0 ];
  403. brackets.push( {
  404. bracket,
  405. textOffset: index - offset
  406. } );
  407. offset++;
  408. }
  409. text = text.replace( regexp, '' );
  410. node._data = text;
  411. const index = node.index;
  412. const parent = node.parent;
  413. // Remove empty text nodes.
  414. if ( !text ) {
  415. node._remove();
  416. }
  417. for ( const item of brackets ) {
  418. // Non-empty text node.
  419. if ( text ) {
  420. if (
  421. this.sameSelectionCharacters ||
  422. (
  423. !this.sameSelectionCharacters &&
  424. ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN )
  425. )
  426. ) {
  427. // Store information about text range delimiter.
  428. this._positions.push( {
  429. bracket: item.bracket,
  430. position: new Position( node, item.textOffset )
  431. } );
  432. } else {
  433. // Check if element range delimiter is not placed inside text node.
  434. if ( !this.sameSelectionCharacters && item.textOffset !== 0 && item.textOffset !== text.length ) {
  435. throw new Error( `Parse error - range delimiter '${ item.bracket }' is placed inside text node.` );
  436. }
  437. // If bracket is placed at the end of the text node - it should be positioned after it.
  438. const offset = ( item.textOffset === 0 ? index : index + 1 );
  439. // Store information about element range delimiter.
  440. this._positions.push( {
  441. bracket: item.bracket,
  442. position: new Position( parent, offset )
  443. } );
  444. }
  445. } else {
  446. if ( !this.sameSelectionCharacters &&
  447. item.bracket == TEXT_RANGE_START_TOKEN ||
  448. item.bracket == TEXT_RANGE_END_TOKEN
  449. ) {
  450. throw new Error( `Parse error - text range delimiter '${ item.bracket }' is placed inside empty text node. ` );
  451. }
  452. // Store information about element range delimiter.
  453. this._positions.push( {
  454. bracket: item.bracket,
  455. position: new Position( parent, index )
  456. } );
  457. }
  458. }
  459. }
  460. }
  461. /**
  462. * Sorts ranges in a given order. Range order should be an array and each element should represent the desired position
  463. * of the range after sorting.
  464. * For example: `[2, 3, 1]` means that the first range will be placed as the second, the second as the third and the third
  465. * as the first.
  466. *
  467. * @private
  468. * @param {Array.<module:engine/view/range~Range>} ranges Ranges to sort.
  469. * @param {Array.<Number>} rangesOrder An array with new range order.
  470. * @returns {Array} Sorted ranges array.
  471. */
  472. _sortRanges( ranges, rangesOrder ) {
  473. const sortedRanges = [];
  474. let index = 0;
  475. for ( const newPosition of rangesOrder ) {
  476. if ( ranges[ newPosition - 1 ] === undefined ) {
  477. throw new Error( 'Parse error - provided ranges order is invalid.' );
  478. }
  479. sortedRanges[ newPosition - 1 ] = ranges[ index ];
  480. index++;
  481. }
  482. return sortedRanges;
  483. }
  484. /**
  485. * Uses all found bracket positions to create ranges from them.
  486. *
  487. * @private
  488. * @returns {Array.<module:engine/view/range~Range>}
  489. */
  490. _createRanges() {
  491. const ranges = [];
  492. let range = null;
  493. for ( const item of this._positions ) {
  494. // When end of range is found without opening.
  495. if ( !range && ( item.bracket == ELEMENT_RANGE_END_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) ) {
  496. throw new Error( `Parse error - end of range was found '${ item.bracket }' but range was not started before.` );
  497. }
  498. // When second start of range is found when one is already opened - selection does not allow intersecting
  499. // ranges.
  500. if ( range && ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) ) {
  501. throw new Error( `Parse error - start of range was found '${ item.bracket }' but one range is already started.` );
  502. }
  503. if ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) {
  504. range = new Range( item.position, item.position );
  505. } else {
  506. range.end = item.position;
  507. ranges.push( range );
  508. range = null;
  509. }
  510. }
  511. // Check if all ranges have proper ending.
  512. if ( range !== null ) {
  513. throw new Error( 'Parse error - range was started but no end delimiter was found.' );
  514. }
  515. return ranges;
  516. }
  517. }
  518. /**
  519. * Private helper class used for converting the view tree to a string.
  520. *
  521. * @private
  522. */
  523. class ViewStringify {
  524. /**
  525. * Creates a view stringify instance.
  526. *
  527. * @param root
  528. * @param {module:engine/view/documentselection~DocumentSelection} selection A selection whose ranges
  529. * should also be converted to a string.
  530. * @param {Object} options An options object.
  531. * @param {Boolean} [options.showType=false] When set to `true`, the type of elements will be printed (`<container:p>`
  532. * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
  533. * @param {Boolean} [options.showPriority=false] When set to `true`, the attribute element's priority will be printed.
  534. * @param {Boolean} [options.ignoreRoot=false] When set to `true`, the root's element opening and closing tag will not
  535. * be outputted.
  536. * @param {Boolean} [options.sameSelectionCharacters=false] When set to `true`, the selection inside the text is marked as
  537. * `{` and `}` and the selection outside the text as `[` and `]`. When set to `false`, both are marked as `[` and `]`.
  538. */
  539. constructor( root, selection, options ) {
  540. this.root = root;
  541. this.selection = selection;
  542. this.ranges = [];
  543. if ( this.selection ) {
  544. this.ranges = [ ...selection.getRanges() ];
  545. }
  546. this.showType = !!options.showType;
  547. this.showPriority = !!options.showPriority;
  548. this.ignoreRoot = !!options.ignoreRoot;
  549. this.sameSelectionCharacters = !!options.sameSelectionCharacters;
  550. }
  551. /**
  552. * Converts the view to a string.
  553. *
  554. * @returns {String} String representation of the view elements.
  555. */
  556. stringify() {
  557. let result = '';
  558. this._walkView( this.root, chunk => {
  559. result += chunk;
  560. } );
  561. return result;
  562. }
  563. /**
  564. * Executes a simple walker that iterates over all elements in the view tree starting from the root element.
  565. * Calls the `callback` with parsed chunks of string data.
  566. *
  567. * @private
  568. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element|module:engine/view/text~Text} root
  569. * @param {Function} callback
  570. */
  571. _walkView( root, callback ) {
  572. const ignore = this.ignoreRoot && this.root === root;
  573. if ( root.is( 'element' ) || root.is( 'documentFragment' ) ) {
  574. if ( root.is( 'element' ) && !ignore ) {
  575. callback( this._stringifyElementOpen( root ) );
  576. }
  577. let offset = 0;
  578. callback( this._stringifyElementRanges( root, offset ) );
  579. for ( const child of root.getChildren() ) {
  580. this._walkView( child, callback );
  581. offset++;
  582. callback( this._stringifyElementRanges( root, offset ) );
  583. }
  584. if ( root.is( 'element' ) && !ignore ) {
  585. callback( this._stringifyElementClose( root ) );
  586. }
  587. }
  588. if ( root.is( 'text' ) ) {
  589. callback( this._stringifyTextRanges( root ) );
  590. }
  591. }
  592. /**
  593. * Checks if a given {@link module:engine/view/element~Element element} has a {@link module:engine/view/range~Range#start range start}
  594. * or a {@link module:engine/view/range~Range#start range end} placed at a given offset and returns its string representation.
  595. *
  596. * @private
  597. * @param {module:engine/view/element~Element} element
  598. * @param {Number} offset
  599. */
  600. _stringifyElementRanges( element, offset ) {
  601. let start = '';
  602. let end = '';
  603. let collapsed = '';
  604. for ( const range of this.ranges ) {
  605. if ( range.start.parent == element && range.start.offset === offset ) {
  606. if ( range.isCollapsed ) {
  607. collapsed += ELEMENT_RANGE_START_TOKEN + ELEMENT_RANGE_END_TOKEN;
  608. } else {
  609. start += ELEMENT_RANGE_START_TOKEN;
  610. }
  611. }
  612. if ( range.end.parent === element && range.end.offset === offset && !range.isCollapsed ) {
  613. end += ELEMENT_RANGE_END_TOKEN;
  614. }
  615. }
  616. return end + collapsed + start;
  617. }
  618. /**
  619. * Checks if a given {@link module:engine/view/element~Element Text node} has a
  620. * {@link module:engine/view/range~Range#start range start} or a
  621. * {@link module:engine/view/range~Range#start range end} placed somewhere inside. Returns a string representation of text
  622. * with range delimiters placed inside.
  623. *
  624. * @private
  625. * @param {module:engine/view/text~Text} node
  626. */
  627. _stringifyTextRanges( node ) {
  628. const length = node.data.length;
  629. let result = node.data.split( '' );
  630. let rangeStartToken, rangeEndToken;
  631. if ( this.sameSelectionCharacters ) {
  632. rangeStartToken = ELEMENT_RANGE_START_TOKEN;
  633. rangeEndToken = ELEMENT_RANGE_END_TOKEN;
  634. } else {
  635. rangeStartToken = TEXT_RANGE_START_TOKEN;
  636. rangeEndToken = TEXT_RANGE_END_TOKEN;
  637. }
  638. // Add one more element for ranges ending after last character in text.
  639. result[ length ] = '';
  640. // Represent each letter as object with information about opening/closing ranges at each offset.
  641. result = result.map( letter => {
  642. return {
  643. letter,
  644. start: '',
  645. end: '',
  646. collapsed: ''
  647. };
  648. } );
  649. for ( const range of this.ranges ) {
  650. const start = range.start;
  651. const end = range.end;
  652. if ( start.parent == node && start.offset >= 0 && start.offset <= length ) {
  653. if ( range.isCollapsed ) {
  654. result[ end.offset ].collapsed += rangeStartToken + rangeEndToken;
  655. } else {
  656. result[ start.offset ].start += rangeStartToken;
  657. }
  658. }
  659. if ( end.parent == node && end.offset >= 0 && end.offset <= length && !range.isCollapsed ) {
  660. result[ end.offset ].end += rangeEndToken;
  661. }
  662. }
  663. return result.map( item => item.end + item.collapsed + item.start + item.letter ).join( '' );
  664. }
  665. /**
  666. * Converts the passed {@link module:engine/view/element~Element element} to an opening tag.
  667. * Depending on the current configuration, the opening tag can be simple (`<a>`), contain a type prefix (`<container:p>`,
  668. * `<attribute:a>` or `<empty:img>`) or contain priority information ( `<attribute:a view-priority="20">` ).
  669. * Element attributes will also be included (`<a href="https://ckeditor.com" name="foobar">`).
  670. *
  671. * @private
  672. * @param {module:engine/view/element~Element} element
  673. * @returns {String}
  674. */
  675. _stringifyElementOpen( element ) {
  676. const priority = this._stringifyElementPriority( element );
  677. const type = this._stringifyElementType( element );
  678. const name = [ type, element.name ].filter( i => i !== '' ).join( ':' );
  679. const attributes = this._stringifyElementAttributes( element );
  680. const parts = [ name, priority, attributes ];
  681. return `<${ parts.filter( i => i !== '' ).join( ' ' ) }>`;
  682. }
  683. /**
  684. * Converts the passed {@link module:engine/view/element~Element element} to a closing tag.
  685. * Depending on the current configuration, the closing tag can be simple (`</a>`) or contain a type prefix (`</container:p>`,
  686. * `</attribute:a>` or `</empty:img>`).
  687. *
  688. * @private
  689. * @param {module:engine/view/element~Element} element
  690. * @returns {String}
  691. */
  692. _stringifyElementClose( element ) {
  693. const type = this._stringifyElementType( element );
  694. const name = [ type, element.name ].filter( i => i !== '' ).join( ':' );
  695. return `</${ name }>`;
  696. }
  697. /**
  698. * Converts the passed {@link module:engine/view/element~Element element's} type to its string representation
  699. *
  700. * Returns:
  701. * * 'attribute' for {@link module:engine/view/attributeelement~AttributeElement attribute elements},
  702. * * 'container' for {@link module:engine/view/containerelement~ContainerElement container elements},
  703. * * 'empty' for {@link module:engine/view/emptyelement~EmptyElement empty elements}.
  704. * * 'ui' for {@link module:engine/view/uielement~UIElement UI elements}.
  705. * * an empty string when the current configuration is preventing showing elements' types.
  706. *
  707. * @private
  708. * @param {module:engine/view/element~Element} element
  709. * @returns {String}
  710. */
  711. _stringifyElementType( element ) {
  712. if ( this.showType ) {
  713. for ( const type in allowedTypes ) {
  714. if ( element instanceof allowedTypes[ type ] ) {
  715. return type;
  716. }
  717. }
  718. }
  719. return '';
  720. }
  721. /**
  722. * Converts the passed {@link module:engine/view/element~Element element} to its priority representation.
  723. * The priority string representation will be returned when the passed element is an instance of
  724. * {@link module:engine/view/attributeelement~AttributeElement attribute element} and the current configuration allows to show the
  725. * priority. Otherwise returns an empty string.
  726. *
  727. * @private
  728. * @param {module:engine/view/element~Element} element
  729. * @returns {String}
  730. */
  731. _stringifyElementPriority( element ) {
  732. if ( this.showPriority && element.is( 'attributeElement' ) ) {
  733. return `view-priority="${ element.priority }"`;
  734. }
  735. return '';
  736. }
  737. /**
  738. * Converts the passed {@link module:engine/view/element~Element element} attributes to their string representation.
  739. * If an element has no attributes, an empty string is returned.
  740. *
  741. * @private
  742. * @param {module:engine/view/element~Element} element
  743. * @returns {String}
  744. */
  745. _stringifyElementAttributes( element ) {
  746. const attributes = [];
  747. const keys = [ ...element.getAttributeKeys() ].sort();
  748. for ( const attribute of keys ) {
  749. let attributeValue;
  750. if ( attribute === 'class' ) {
  751. attributeValue = [ ...element.getClassNames() ]
  752. .sort()
  753. .join( ' ' );
  754. } else if ( attribute === 'style' ) {
  755. attributeValue = [ ...element.getStyleNames() ]
  756. .sort()
  757. .map( style => `${ style }:${ element.getStyle( style ) }` )
  758. .join( ';' );
  759. } else {
  760. attributeValue = element.getAttribute( attribute );
  761. }
  762. attributes.push( `${ attribute }="${ attributeValue }"` );
  763. }
  764. return attributes.join( ' ' );
  765. }
  766. }
  767. // Converts {@link module:engine/view/element~Element elements} to
  768. // {@link module:engine/view/attributeelement~AttributeElement attribute elements},
  769. // {@link module:engine/view/containerelement~ContainerElement container elements},
  770. // {@link module:engine/view/emptyelement~EmptyElement empty elements} or
  771. // {@link module:engine/view/uielement~UIElement UI elements}.
  772. // It converts the whole tree starting from the `rootNode`. The conversion is based on element names.
  773. // See the `_convertElement` method for more details.
  774. //
  775. // @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|module:engine/view/text~Text}
  776. // rootNode The root node to convert.
  777. // @returns {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|
  778. // module:engine/view/text~Text} The root node of converted elements.
  779. function _convertViewElements( rootNode ) {
  780. if ( rootNode.is( 'element' ) || rootNode.is( 'documentFragment' ) ) {
  781. // Convert element or leave document fragment.
  782. const convertedElement = rootNode.is( 'documentFragment' ) ? new ViewDocumentFragment() : _convertElement( rootNode );
  783. // Convert all child nodes.
  784. // Cache the nodes in array. Otherwise, we would skip some nodes because during iteration we move nodes
  785. // from `rootNode` to `convertedElement`. This would interfere with iteration.
  786. for ( const child of [ ...rootNode.getChildren() ] ) {
  787. if ( convertedElement.is( 'emptyElement' ) ) {
  788. throw new Error( 'Parse error - cannot parse inside EmptyElement.' );
  789. }
  790. if ( convertedElement.is( 'uiElement' ) ) {
  791. throw new Error( 'Parse error - cannot parse inside UIElement.' );
  792. }
  793. convertedElement._appendChildren( _convertViewElements( child ) );
  794. }
  795. return convertedElement;
  796. }
  797. return rootNode;
  798. }
  799. // Converts an {@link module:engine/view/element~Element element} to
  800. // {@link module:engine/view/attributeelement~AttributeElement attribute element},
  801. // {@link module:engine/view/containerelement~ContainerElement container element},
  802. // {@link module:engine/view/emptyelement~EmptyElement empty element} or
  803. // {@link module:engine/view/uielement~UIElement UI element}.
  804. // If the element's name is in the format of `attribute:b` with `view-priority="11"` attribute, it will be converted to
  805. // an {@link module:engine/view/attributeelement~AttributeElement attribute element} with a priority of 11.
  806. // If the element's name is in the format of `container:p`, it will be converted to
  807. // a {@link module:engine/view/containerelement~ContainerElement container element}.
  808. // If the element's name is in the format of `empty:img`, it will be converted to
  809. // an {@link module:engine/view/emptyelement~EmptyElement empty element}.
  810. // If the element's name is in the format of `ui:span`, it will be converted to
  811. // a {@link module:engine/view/uielement~UIElement UI element}.
  812. // If the element's name does not contain any additional information, a {@link module:engine/view/element~Element view Element} will be
  813. // returned.
  814. //
  815. // @param {module:engine/view/element~Element} viewElement A view element to convert.
  816. // @returns {module:engine/view/element~Element|module:engine/view/attributeelement~AttributeElement|
  817. // module:engine/view/emptyelement~EmptyElement|module:engine/view/uielement~UIElement|
  818. // module:engine/view/containerelement~ContainerElement} A tree view
  819. // element converted according to its name.
  820. function _convertElement( viewElement ) {
  821. const info = _convertElementNameAndPriority( viewElement );
  822. const ElementConstructor = allowedTypes[ info.type ];
  823. const newElement = ElementConstructor ? new ElementConstructor( info.name ) : new ViewElement( info.name );
  824. if ( newElement.is( 'attributeElement' ) ) {
  825. if ( info.priority !== null ) {
  826. newElement._priority = info.priority;
  827. }
  828. }
  829. // Move attributes.
  830. for ( const attributeKey of viewElement.getAttributeKeys() ) {
  831. newElement._setAttribute( attributeKey, viewElement.getAttribute( attributeKey ) );
  832. }
  833. return newElement;
  834. }
  835. // Converts the `view-priority` attribute and the {@link module:engine/view/element~Element#name element's name} information needed for
  836. // creating {@link module:engine/view/attributeelement~AttributeElement attribute element},
  837. // {@link module:engine/view/containerelement~ContainerElement container element},
  838. // {@link module:engine/view/emptyelement~EmptyElement empty element} or
  839. // {@link module:engine/view/uielement~UIElement UI element}.
  840. // The name can be provided in two formats: as a simple element's name (`div`), or as a type and name (`container:div`,
  841. // `attribute:span`, `empty:img`, `ui:span`);
  842. //
  843. // @param {module:engine/view/element~Element} element The element whose name should be converted.
  844. // @returns {Object} info An object with parsed information.
  845. // @returns {String} info.name The parsed name of the element.
  846. // @returns {String|null} info.type The parsed type of the element. It can be `attribute`, `container` or `empty`.
  847. // returns {Number|null} info.priority The parsed priority of the element.
  848. function _convertElementNameAndPriority( viewElement ) {
  849. const parts = viewElement.name.split( ':' );
  850. const priority = _convertPriority( viewElement.getAttribute( 'view-priority' ) );
  851. viewElement._removeAttribute( 'view-priority' );
  852. if ( parts.length == 1 ) {
  853. return {
  854. name: parts[ 0 ],
  855. type: priority !== null ? 'attribute' : null,
  856. priority
  857. };
  858. }
  859. // Check if type and name: container:div.
  860. const type = _convertType( parts[ 0 ] );
  861. if ( type ) {
  862. return {
  863. name: parts[ 1 ],
  864. type,
  865. priority
  866. };
  867. }
  868. throw new Error( `Parse error - cannot parse element's name: ${ viewElement.name }.` );
  869. }
  870. // Checks if the element's type is allowed. Returns `attribute`, `container`, `empty` or `null`.
  871. //
  872. // @param {String} type
  873. // @returns {String|null}
  874. function _convertType( type ) {
  875. return allowedTypes[ type ] ? type : null;
  876. }
  877. // Checks if a given priority is allowed. Returns null if the priority cannot be converted.
  878. //
  879. // @param {String} priorityString
  880. // returns {Number|Null}
  881. function _convertPriority( priorityString ) {
  882. const priority = parseInt( priorityString, 10 );
  883. if ( !isNaN( priority ) ) {
  884. return priority;
  885. }
  886. return null;
  887. }