8
0

view.js 41 KB

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