8
0

view.js 34 KB

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