view.js 41 KB

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