view.js 32 KB

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