8
0

view.js 32 KB

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