8
0

view.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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. /**
  20. * Writes the contents of the {@link engine.view.Document Document} to an HTML-like string.
  21. *
  22. * @param {engine.view.Document} document
  23. * @param {Object} [options]
  24. * @param {Boolean} [options.withoutSelection=false] Whether to write the selection. When set to `true` selection will
  25. * be not included in returned string.
  26. * @param {Boolean} [options.rootName='main'] Name of the root from which data should be stringified. If not provided
  27. * default `main` name will be used.
  28. * @param {Boolean} [options.showType=false] When set to `true` type of elements will be printed (`<container:p>`
  29. * instead of `<p>` and `<attribute:b>` instead of `<b>`).
  30. * @param {Boolean} [options.showPriority=false] When set to `true` AttributeElement's priority will be printed
  31. * (`<span:12>`, `<b:10>`).
  32. * @returns {String} The stringified data.
  33. */
  34. export function getData( document, options = {} ) {
  35. if ( !( document instanceof Document ) ) {
  36. throw new TypeError( 'Document needs to be an instance of engine.view.Document.' );
  37. }
  38. const withoutSelection = !!options.withoutSelection;
  39. const rootName = options.rootName || 'main';
  40. const root = document.getRoot( rootName );
  41. const stringifyOptions = {
  42. showType: options.showType,
  43. showPriority: options.showPriority,
  44. ignoreRoot: true
  45. };
  46. return withoutSelection ?
  47. getData._stringify( root, null, stringifyOptions ) :
  48. getData._stringify( root, document.selection, stringifyOptions );
  49. }
  50. // Set stringify as getData private method - needed for testing/spying.
  51. getData._stringify = stringify;
  52. /**
  53. * Sets the contents of the {@link engine.view.Document Document} provided as HTML-like string.
  54. *
  55. * @param {engine.view.Document} document
  56. * @param {String} data HTML-like string to write into Document.
  57. * @param {Object} options
  58. * @param {String} [options.rootName='main'] Root name where parsed data will be stored. If not provided,
  59. * default `main` name will be used.
  60. */
  61. export function setData( document, data, options = {} ) {
  62. if ( !( document instanceof Document ) ) {
  63. throw new TypeError( 'Document needs to be an instance of engine.view.Document.' );
  64. }
  65. const rootName = options.rootName || 'main';
  66. const root = document.getRoot( rootName );
  67. const result = setData._parse( data, { rootElement: root } );
  68. if ( result.view && result.selection ) {
  69. document.selection.setTo( result.selection );
  70. }
  71. }
  72. // Set parse as setData private method - needed for testing/spying.
  73. setData._parse = parse;
  74. /**
  75. * Converts view elements to HTML-like string representation.
  76. * Root element can be provided as {@link engine.view.Text Text}:
  77. *
  78. * const text = new Text( 'foobar' );
  79. * stringify( text ); // 'foobar'
  80. *
  81. * or as {@link engine.view.Element Element}:
  82. *
  83. * const element = new Element( 'p', null, new Text( 'foobar' ) );
  84. * stringify( element ); // '<p>foobar</p>'
  85. *
  86. * or as {@link engine.view.DocumentFragment DocumentFragment}:
  87. *
  88. * const text = new Text( 'foobar' );
  89. * const b = new Element( 'b', { name: 'test' }, text );
  90. * const p = new Element( 'p', { style: 'color:red;' } );
  91. * const fragment = new DocumentFragment( [ p, b ] );
  92. *
  93. * stringify( fragment ); // '<p style="color:red;"></p><b name="test">foobar</b>'
  94. *
  95. * Additionally {@link engine.view.Selection Selection} instance can be provided, then ranges from that selection
  96. * will be included in output data.
  97. * If range position is placed inside element node, it will be represented with `[` and `]`:
  98. *
  99. * const text = new Text( 'foobar' );
  100. * const b = new Element( 'b', null, text );
  101. * const p = new Element( 'p', null, b );
  102. * const selection = new Selection();
  103. * selection.addRange( Range.createFromParentsAndOffsets( p, 0, p, 1 ) );
  104. *
  105. * stringify( p, selection ); // '<p>[<b>foobar</b>]</p>'
  106. *
  107. * If range is placed inside text node, it will be represented with `{` and `}`:
  108. *
  109. * const text = new Text( 'foobar' );
  110. * const b = new Element( 'b', null, text );
  111. * const p = new Element( 'p', null, b );
  112. * const selection = new Selection();
  113. * selection.addRange( Range.createFromParentsAndOffsets( text, 1, text, 5 ) );
  114. *
  115. * stringify( p, selection ); // '<p><b>f{ooba}r</b></p>'
  116. *
  117. * NOTE:
  118. * Characters representing range placed inside text are customizable by `characterForSelectionInText` option.
  119. * It is mainly needed when view stringify function is used by model stringify util, then range
  120. * is represented with `[` and `]`.
  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:20></b:20>
  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:12>`, `<b: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 {Array<String>} [options.characterForSelectionInText=['{','}']] At default range placed inside text is
  173. * represented with `{` and `}` characters, but when stringify function is used by model stringify util then characters
  174. * are changed to `[` and `]`.
  175. * @returns {String} HTML-like string representing the view.
  176. */
  177. export function stringify( node, selectionOrPositionOrRange = null, options = {} ) {
  178. let selection;
  179. if ( selectionOrPositionOrRange instanceof Position ) {
  180. selection = new Selection();
  181. selection.addRange( new Range( selectionOrPositionOrRange, selectionOrPositionOrRange ) );
  182. } else if ( selectionOrPositionOrRange instanceof Range ) {
  183. selection = new Selection();
  184. selection.addRange( selectionOrPositionOrRange );
  185. } else {
  186. selection = selectionOrPositionOrRange;
  187. }
  188. if ( !options.characterForSelectionInText ) {
  189. options.characterForSelectionInText = [ TEXT_RANGE_START_TOKEN, TEXT_RANGE_END_TOKEN ];
  190. }
  191. const viewStringify = new ViewStringify( node, selection, options );
  192. return viewStringify.stringify();
  193. }
  194. /**
  195. * Parses HTML-like string and returns view tree nodes.
  196. * Simple string will be converted to {@link engine.view.Text Text} node:
  197. *
  198. * parse( 'foobar' ); // Returns instance of Text.
  199. *
  200. * {@link engine.view.Element Elements} will be parsed with attributes an children:
  201. *
  202. * parse( '<b name="baz">foobar</b>' ); // Returns instance of Element with `baz` attribute and text child node.
  203. *
  204. * Multiple nodes provided on root level will be converted to {@link engine.view.DocumentFragment DocumentFragment}:
  205. *
  206. * parse( '<b>foo</b><i>bar</i>' ); // Returns DocumentFragment with two child elements.
  207. *
  208. * Method can parse multiple {@link engine.view.Range ranges} provided in string data and return
  209. * {@link engine.view.Selection Selection} instance containing these ranges. Ranges placed inside
  210. * {@link engine.view.Text Text} nodes should be marked using `{` and `}` brackets:
  211. *
  212. * const { text, selection } = parse( 'f{ooba}r' );
  213. *
  214. * Ranges placed outside text nodes should be marked using `[` and `]` brackets:
  215. *
  216. * const { root, selection } = parse( '<p>[<b>foobar</b>]</p>' );
  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. * @returns {engine.view.Text|engine.view.Element|engine.view.DocumentFragment|Object} Returns parsed view node
  255. * or object with two fields `view` and `selection` when selection ranges were included in data to parse.
  256. */
  257. export function parse( data, options = {} ) {
  258. options.order = options.order || [];
  259. const rangeParser = new RangeParser();
  260. const processor = new HtmlDataProcessor();
  261. // Convert data to view.
  262. let view = processor.toView( data );
  263. // At this point we have a view tree with Elements that could have names like `attribute:b:1`. In the next step
  264. // we need to parse Element's names and convert them to AttributeElements and ContainerElements.
  265. view = _convertViewElements( view );
  266. // If custom root is provided - move all nodes there.
  267. if ( options.rootElement ) {
  268. const root = options.rootElement;
  269. const nodes = view.removeChildren( 0, view.childCount );
  270. root.removeChildren( 0, root.childCount );
  271. root.appendChildren( nodes );
  272. view = root;
  273. }
  274. // Parse ranges included in view text nodes.
  275. const ranges = rangeParser.parse( view, options.order );
  276. // If only one element is returned inside DocumentFragment - return that element.
  277. if ( view instanceof ViewDocumentFragment && view.childCount === 1 ) {
  278. view = view.getChild( 0 );
  279. }
  280. // When ranges are present - return object containing view, and selection.
  281. if ( ranges.length ) {
  282. const selection = new Selection();
  283. selection.setRanges( ranges, !!options.lastRangeBackward );
  284. return {
  285. view: view,
  286. selection: selection
  287. };
  288. }
  289. // If single element is returned without selection - remove it from parent and return detached element.
  290. if ( view.parent ) {
  291. view.remove();
  292. }
  293. return view;
  294. }
  295. /**
  296. * Private helper class used for converting ranges represented as text inside view {@link engine.view.Text Text nodes}.
  297. *
  298. * @private
  299. */
  300. class RangeParser {
  301. /**
  302. * Parses the view, and returns ranges represented inside {@link engine.view.Text Text nodes}.
  303. * Method will remove all occurrences of `{`, `}`, `[` and `]` from found text nodes. If text node is empty after
  304. * the process - it will be removed too.
  305. *
  306. * @param {engine.view.Node} node Starting node.
  307. * @param {Array.<Number>} order Ranges order. Each element should represent desired position of the range after
  308. * sorting. For example: `[2, 3, 1]` means that first range will be placed as second, second as third and third as first.
  309. * @returns {Array.<engine.view.Range>} Array with ranges found.
  310. */
  311. parse( node, order ) {
  312. this._positions = [];
  313. // Remove all range brackets from view nodes and save their positions.
  314. this._getPositions( node );
  315. // Create ranges using gathered positions.
  316. let ranges = this._createRanges();
  317. // Sort ranges if needed.
  318. if ( order.length ) {
  319. if ( order.length != ranges.length ) {
  320. throw new Error(
  321. `Parse error - there are ${ ranges.length } ranges found, but ranges order array contains ${ order.length } elements.`
  322. );
  323. }
  324. ranges = this._sortRanges( ranges, order );
  325. }
  326. return ranges;
  327. }
  328. /**
  329. * Gathers positions of brackets inside view tree starting from provided node. Method will remove all occurrences of
  330. * `{`, `}`, `[` and `]` from found text nodes. If text node is empty after the process - it will be removed
  331. * too.
  332. *
  333. * @private
  334. * @param {engine.view.Node} node Staring node.
  335. */
  336. _getPositions( node ) {
  337. if ( node instanceof ViewDocumentFragment || node instanceof ViewElement ) {
  338. // Copy elements into the array, when nodes will be removed from parent node this array will still have all the
  339. // items needed for iteration.
  340. const children = [ ...node.getChildren() ];
  341. for ( let child of children ) {
  342. this._getPositions( child );
  343. }
  344. }
  345. if ( node instanceof ViewText ) {
  346. const regexp = new RegExp(
  347. `[${ TEXT_RANGE_START_TOKEN }${ TEXT_RANGE_END_TOKEN }\\${ ELEMENT_RANGE_END_TOKEN }\\${ ELEMENT_RANGE_START_TOKEN }]`,
  348. 'g'
  349. );
  350. let text = node.data;
  351. let match;
  352. let offset = 0;
  353. const brackets = [];
  354. // Remove brackets from text and store info about offset inside text node.
  355. while ( ( match = regexp.exec( text ) ) ) {
  356. const index = match.index;
  357. const bracket = match[ 0 ];
  358. brackets.push( {
  359. bracket: bracket,
  360. textOffset: index - offset
  361. } );
  362. offset++;
  363. }
  364. text = text.replace( regexp, '' );
  365. node.data = text;
  366. const index = node.index;
  367. const parent = node.parent;
  368. // Remove empty text nodes.
  369. if ( !text ) {
  370. node.remove();
  371. }
  372. for ( let item of brackets ) {
  373. // Non-empty text node.
  374. if ( text ) {
  375. if ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) {
  376. // Store information about text range delimiter.
  377. this._positions.push( {
  378. bracket: item.bracket,
  379. position: new Position( node, item.textOffset )
  380. } );
  381. } else {
  382. // Check if element range delimiter is not placed inside text node.
  383. if ( item.textOffset !== 0 && item.textOffset !== text.length ) {
  384. throw new Error( `Parse error - range delimiter '${ item.bracket }' is placed inside text node.` );
  385. }
  386. // If bracket is placed at the end of the text node - it should be positioned after it.
  387. const offset = ( item.textOffset === 0 ? index : index + 1 );
  388. // Store information about element range delimiter.
  389. this._positions.push( {
  390. bracket: item.bracket,
  391. position: new Position( parent, offset )
  392. } );
  393. }
  394. } else {
  395. if ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) {
  396. throw new Error( `Parse error - text range delimiter '${ item.bracket }' is placed inside empty text node. ` );
  397. }
  398. // Store information about element range delimiter.
  399. this._positions.push( {
  400. bracket: item.bracket,
  401. position: new Position( parent, index )
  402. } );
  403. }
  404. }
  405. }
  406. }
  407. /**
  408. * Sort ranges in given order. Ranges order should be an array, each element should represent desired position
  409. * of the range after sorting.
  410. * For example: `[2, 3, 1]` means that first range will be placed as second, second as third and third as first.
  411. *
  412. * @private
  413. * @param {Array.<engine.view.Range>} ranges Ranges to sort.
  414. * @param {Array.<Number>} rangesOrder Array with new ranges order.
  415. * @returns {Array} Sorted ranges array.
  416. */
  417. _sortRanges( ranges, rangesOrder ) {
  418. const sortedRanges = [];
  419. let index = 0;
  420. for ( let newPosition of rangesOrder ) {
  421. if ( ranges[ newPosition - 1 ] === undefined ) {
  422. throw new Error( 'Parse error - provided ranges order is invalid.' );
  423. }
  424. sortedRanges[ newPosition - 1 ] = ranges[ index ];
  425. index++;
  426. }
  427. return sortedRanges;
  428. }
  429. /**
  430. * Uses all found bracket positions to create ranges from them.
  431. *
  432. * @private
  433. * @returns {Array.<engine.view.Range>}
  434. */
  435. _createRanges() {
  436. const ranges = [];
  437. let range = null;
  438. for ( let item of this._positions ) {
  439. // When end of range is found without opening.
  440. if ( !range && ( item.bracket == ELEMENT_RANGE_END_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) ) {
  441. throw new Error( `Parse error - end of range was found '${ item.bracket }' but range was not started before.` );
  442. }
  443. // When second start of range is found when one is already opened - selection does not allow intersecting
  444. // ranges.
  445. if ( range && ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) ) {
  446. throw new Error( `Parse error - start of range was found '${ item.bracket }' but one range is already started.` );
  447. }
  448. if ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) {
  449. range = new Range( item.position, item.position );
  450. } else {
  451. range.end = item.position;
  452. ranges.push( range );
  453. range = null;
  454. }
  455. }
  456. // Check if all ranges have proper ending.
  457. if ( range !== null ) {
  458. throw new Error( 'Parse error - range was started but no end delimiter was found.' );
  459. }
  460. return ranges;
  461. }
  462. }
  463. /**
  464. * Private helper class used for converting view tree to string.
  465. *
  466. * @private
  467. */
  468. class ViewStringify {
  469. /**
  470. * Creates ViewStringify instance.
  471. *
  472. * @param root
  473. * @param {engine.view.Selection} [selection=null] Selection which ranges should be also converted to string.
  474. * @param {Object} [options] Options object.
  475. * @param {Boolean} [options.showType=false] When set to `true` type of elements will be printed ( `<container:p>`
  476. * instead of `<p>` and `<attribute:b>` instead of `<b>`.
  477. * @param {Boolean} [options.showPriority=false] When set to `true` AttributeElement's priority will be printed.
  478. * @param {Boolean} [options.ignoreRoot=false] When set to `true` root's element opening and closing tag will not
  479. * be outputted.
  480. * @param {Array<String>} [options.characterForSelectionInText = [ '{', '}' ]
  481. */
  482. constructor( root, selection = null, options = {} ) {
  483. this.root = root;
  484. this.selection = selection;
  485. this.ranges = [];
  486. if ( this.selection ) {
  487. this.ranges = [ ...selection.getRanges() ];
  488. }
  489. this.showType = !!options.showType;
  490. this.showPriority = !!options.showPriority;
  491. this.ignoreRoot = !!options.ignoreRoot;
  492. this.characterForSelectionInText = options.characterForSelectionInText;
  493. }
  494. /**
  495. * Converts view to string.
  496. *
  497. * @returns {String} String representation of the view elements.
  498. */
  499. stringify() {
  500. let result = '';
  501. this._walkView( this.root, ( chunk ) => {
  502. result += chunk;
  503. } );
  504. return result;
  505. }
  506. /**
  507. * Executes simple walker that iterates over all elements in the view tree starting from root element.
  508. * Calls `callback` with parsed chunks of string data.
  509. *
  510. * @private
  511. * @param {engine.view.DocumentFragment|engine.view.Element|engine.view.Text} root
  512. * @param {Function} callback
  513. */
  514. _walkView( root, callback ) {
  515. const isElement = root instanceof ViewElement;
  516. const ignore = this.ignoreRoot && this.root === root;
  517. if ( isElement || root instanceof ViewDocumentFragment ) {
  518. if ( isElement && !ignore ) {
  519. callback( this._stringifyElementOpen( root ) );
  520. }
  521. let offset = 0;
  522. callback( this._stringifyElementRanges( root, offset ) );
  523. for ( let child of root.getChildren() ) {
  524. this._walkView( child, callback );
  525. offset++;
  526. callback( this._stringifyElementRanges( root, offset ) );
  527. }
  528. if ( isElement && !ignore ) {
  529. callback( this._stringifyElementClose( root ) );
  530. }
  531. }
  532. if ( root instanceof ViewText ) {
  533. callback( this._stringifyTextRanges( root ) );
  534. }
  535. }
  536. /**
  537. * Checks if given {@link engine.view.Element Element} has {@link engine.view.Range#start range start} or
  538. * {@link engine.view.Range#start range end} placed at given offset and returns its string representation.
  539. *
  540. * @private
  541. * @param {engine.view.Element} element
  542. * @param {Number} offset
  543. */
  544. _stringifyElementRanges( element, offset ) {
  545. let start = '';
  546. let end = '';
  547. let collapsed = '';
  548. for ( let range of this.ranges ) {
  549. if ( range.start.parent == element && range.start.offset === offset ) {
  550. if ( range.isCollapsed ) {
  551. collapsed += ELEMENT_RANGE_START_TOKEN + ELEMENT_RANGE_END_TOKEN;
  552. } else {
  553. start += ELEMENT_RANGE_START_TOKEN;
  554. }
  555. }
  556. if ( range.end.parent === element && range.end.offset === offset && !range.isCollapsed ) {
  557. end += ELEMENT_RANGE_END_TOKEN;
  558. }
  559. }
  560. return end + collapsed + start;
  561. }
  562. /**
  563. * Checks if given {@link engine.view.Element Text node} has {@link engine.view.Range#start range start} or
  564. * {@link engine.view.Range#start range end} placed somewhere inside. Returns string representation of text
  565. * with range delimiters placed inside.
  566. *
  567. * @private
  568. * @param {engine.view.Text} node
  569. */
  570. _stringifyTextRanges( node ) {
  571. const length = node.data.length;
  572. let result = node.data.split( '' );
  573. // Add one more element for ranges ending after last character in text.
  574. result[ length ] = '';
  575. // Represent each letter as object with information about opening/closing ranges at each offset.
  576. result = result.map( ( letter ) => {
  577. return {
  578. letter: letter,
  579. start: '',
  580. end: '',
  581. collapsed: ''
  582. };
  583. } );
  584. for ( let range of this.ranges ) {
  585. const start = range.start;
  586. const end = range.end;
  587. if ( start.parent == node && start.offset >= 0 && start.offset <= length ) {
  588. if ( range.isCollapsed ) {
  589. result[ end.offset ].collapsed += this.characterForSelectionInText.join( '' );
  590. } else {
  591. result[ start.offset ].start += this.characterForSelectionInText[ 0 ];
  592. }
  593. }
  594. if ( end.parent == node && end.offset >= 0 && end.offset <= length && !range.isCollapsed ) {
  595. result[ end.offset ].end += this.characterForSelectionInText[ 1 ];
  596. }
  597. }
  598. return result.map( item => item.end + item.collapsed + item.start + item.letter ).join( '' );
  599. }
  600. /**
  601. * Converts passed {@link engine.view.Element Element} to opening tag.
  602. * Depending on current configuration opening tag can be simple (`<a>`), contain type prefix (`<container:p>` or
  603. * `<attribute:a>`), contain priority information ( `<attribute:a priority=20>` ). Element's attributes also
  604. * will be included (`<a href="http://ckeditor.com" name="foobar">`).
  605. *
  606. * @private
  607. * @param {engine.view.Element} element
  608. * @returns {String}
  609. */
  610. _stringifyElementOpen( element ) {
  611. const priority = this._stringifyElementPriority( element );
  612. const type = this._stringifyElementType( element );
  613. const name = [ type, element.name, priority ].filter( i=> i !== '' ).join( ':' );
  614. const attributes = this._stringifyElementAttributes( element );
  615. const parts = [ name, attributes ];
  616. return `<${ parts.filter( i => i !== '' ).join( ' ' ) }>`;
  617. }
  618. /**
  619. * Converts passed {@link engine.view.Element Element} to closing tag.
  620. * Depending on current configuration opening tag can be simple (`</a>`) or contain type prefix (`</container:p>` or
  621. * `</attribute:a>`).
  622. *
  623. * @private
  624. * @param {engine.view.Element} element
  625. * @returns {String}
  626. */
  627. _stringifyElementClose( element ) {
  628. const priority = this._stringifyElementPriority( element );
  629. const type = this._stringifyElementType( element );
  630. const name = [ type, element.name, priority ].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 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:1` or `b:11` 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. const info = _convertElementName( viewElement );
  721. let newElement;
  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 {@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 couple formats: as a simple element's name (`div`), as a type and name (`container:div`,
  741. // `attribute:span`), as a name and priority (`span:12`) and as a type, priority, name trio (`attribute:span:12`);
  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 _convertElementName( viewElement ) {
  749. const parts = viewElement.name.split( ':' );
  750. if ( parts.length == 1 ) {
  751. return {
  752. name: parts[ 0 ],
  753. type: null,
  754. priority: null
  755. };
  756. }
  757. if ( parts.length == 2 ) {
  758. // Check if type and name: container:div.
  759. const type = _convertType( parts[ 0 ] );
  760. if ( type ) {
  761. return {
  762. name: parts[ 1 ],
  763. type: type,
  764. priority: null
  765. };
  766. }
  767. // Check if name and priority: span:10.
  768. const priority = _convertPriority( parts[ 1 ] );
  769. if ( priority !== null ) {
  770. return {
  771. name: parts[ 0 ],
  772. type: 'attribute',
  773. priority: priority
  774. };
  775. }
  776. throw new Error( `Parse error - cannot parse element's name: ${ viewElement.name }.` );
  777. }
  778. // Check if name is in format type:name:priority.
  779. if ( parts.length === 3 ) {
  780. const type = _convertType( parts[ 0 ] );
  781. const priority = _convertPriority( parts[ 2 ] );
  782. if ( type && priority !== null ) {
  783. return {
  784. name: parts[ 1 ],
  785. type: type,
  786. priority: priority
  787. };
  788. }
  789. }
  790. throw new Error( `Parse error - cannot parse element's tag name: ${ viewElement.name }.` );
  791. }
  792. // Checks if element's type is allowed. Returns `attribute`, `container` or `null`.
  793. //
  794. // @param {String} type
  795. // @returns {String|null}
  796. function _convertType( type ) {
  797. if ( type == 'container' || type == 'attribute' ) {
  798. return type;
  799. }
  800. return null;
  801. }
  802. // Checks if given priority is allowed. Returns null if priority cannot be converted.
  803. //
  804. // @param {String} priorityString
  805. // returns {Number|Null}
  806. function _convertPriority( priorityString ) {
  807. const priority = parseInt( priorityString, 10 );
  808. if ( !isNaN( priority ) ) {
  809. return priority;
  810. }
  811. return null;
  812. }