8
0

view.js 34 KB

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