view.js 43 KB

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