view.js 33 KB

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